Mongoose
What is Monoose?
Connect MongoDB
Create Model
Populate
What is Mongoose?
Mongoose is the Object Document Mapper (ODM) for Node.js and it is written on the top of the Node.js native MongoDB driver.
Connect MongoDB
const mongoose = require('mongoose');
function connect () {
const connection = mongoose.connect('mongodb://localhost:27017/dashboard-api');
return connection;
};
connect()
.then(function() {
console.log('DB connect established');
listen();
})
.catch(function() {
console.error('DB connection error.');
});
Define Model
Populate
aggregate
Count
User.count({
region: 'North'
}, function (err, result) {
if (err) {
next(err);
} else {
res.json(result);
}
});
Distinct
User.distinct("region", function (err, result) {
if (err) {
next(err);
} else {
res.json(result);
}
});