Koneksi
const mongoose = require('mongoose');
const URL = "mongodb://user:[email protected]:27017/database?authSource=admin";
mongoose.connect(URL, {"server":{"auto_reconnect":true}});
var db = mongoose.connection;
db.on('error', function(err) {
console.error('Error in MongoDB connection: ' + err);
});
db.on('connected', function() {
console.log('Connected to MongoDB');
});
Model
Anda membuat skema yang mewakili koleksi di db Anda
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const MyModel = Schema({
foo: String
}, { collection: 'mycollection' });
module.exports = mongoose.model('MyModel', MyModelSchema);
Pengontrol
Anda menggunakan skema ini untuk mengeksekusi permintaan ke koleksi itu
const MyModel = require('../models/mymodel');
function myFunction(req, res) {
MyModel.find({}).exec(function(err, result){
if(!result) return res.status(404).send();
var array = [];
result.map(function(data){
array.push(data.foo);
});
res.status(200).send({"mydata": array});
});
}
module.exports = {
myFunction
};