MongoDB and Mongoose - Arquisoft/radarin_en2b GitHub Wiki
MongoDB
MongoDB is a NoSQL database system which stores data in the form of BSON (binary representation of JSON) documents. In terms of Node.js, mongodb is the native driver for interacting with a mongodb instance and mongoose is an Object modeling tool for MongoDB.
Installing Mongoose and MongoDB
First, we need to install mongoose if it is not already done. Mongoose is installed in (package.json) like any other dependency using npm:
npm install mongoose
To be able to use schema definitions for GeoJSON types we need first to have installed node.js, mongodb and mogoose. documentation
npm install mongoose-geojson-schema --save
In order to run the mongo db database we only need docker as it is the manager of doing it.
Connecting to MongoDB
// import the mongoose module
const mongoose = require("mongoose")
// example of setting up a default mongoose connection
mongoose.connect('mongodb://localhost:27017/myapp', {useNewUrlParser: true, useUnifiedTopology: true});
// or (if we want and need to specify several more paramentes in the uri)
mongoose.connect('mongodb://username:password@host:port/database?options...', {useNewUrlParser: true, useUnifiedTopology: true});
// to handle initial connection errors
mongoose.connect(...).catch(error => handleError(error));
// to handle errors after initial connection was established, we should listen for error events on the connection.
mongoose.connection.on('error', err => {
logError(err);
});
Queries
In the following link (here) there are lots of query methods and examples of how to do them.
We can also use helper functions that mongoose models provides us for CRUD operations. Each of these functions returns a mongoose query object. Link to the documentation here
To make a query which specifies a GeoJSON data (in this case a point), $near operator requires a 2dsphere index and has the following syntax and considering a collection places:
db.places.find(
{
location:
{ $near :
{
$geometry: { type: "Point", coordinates: [ -73.9667, 40.78 ] },
$minDistance: 1000,
$maxDistance: 5000
}
}
}
)
If specifying latitude and longitude coordinates as in the example before, list the longitude first and then latitude:
- Valid longitude values are between -180 and 180, both inclusive.
- Valid latitude values are between -90 and 90, both inclusive.
The query returns documents that are at least 1000 meters from and at most 5000 meters from the specified GeoJSON point, sorted from nearest to farthest.
Schema
Mongoose schemas have a timestamps option that tells Mongoose to automatically manage createdAt and updatedAt properties on your documents. For example, here's how you can enable timestamps on a User model.
When you enable timestamps, Mongoose adds createdAt and updatedAt properties to your schema. By default, createdAt and updatedAt are of type Date. When you update a document, Mongoose automatically increments updatedAt.
const GeoJSON = require('mongoose-geojson-schema')
const mongoose = require("mongoose")
const schema = mongoose.Schema(
{
webId: String,
location: mongoose.Schema.Types.Point,
authKey: String
},
{ timestamps: true }
);
const User = mongoose.model("User", schema); // User is a collection
const doc = await User.create({ webId: "https://in..../user/asdfg",
location: {
type: "Point",
coordinates: [43.53573, -5.66152 ]
},
authKey: "auth123456789"});
doc.createdAt; // 2020-07-06T20:36:59.414Z
doc.updatedAt; // 2020-07-06T20:36:59.414Z
doc.createdAt instanceof Date; // true
Another option is to have the timestamps disabled (default behaviour) and do it manually as following but in my opinion the first is the best option:
const schema = mongoose.Schema({
webId: String,
location: mongoose.Schema.Types.Point,
timestamp: Date,
authKey: String
})
var user = {
webId: "https://in..../user/asdfg",
location: {
type: "Point",
coordinates: [43.53573, -5.66152 ]
},
timestamp: ISODate("2021-02-28T12:00:00.000Z"),
authKey: "auth123456789"
}
module.exports = mongoose.model("User", schema)
Indexes
Indexes support the efficient execution of queries in MongoDB. Without indexes, MongoDB must perform a collection scan, i.e. scan every document in a collection, to select those documents that match the query statement.
More useful documentation
To look for a complete guide about schemas, schema types, connections, models, documents, subdocuments, queries, etc click here.