my node.js application has one mongodb (db1) which has user details. Each user has different db(mongodb). So I maintain all the db information in db1.
Here my question is based on user I need to open user db connection at runtime and perform some operation in user db.
Please help me how to do.
my app.js is.
var mongoose = require("mongoose");
var conn = mongoose.createConnection('mongodb://localhost/testA');
var conn2 = mongoose.createConnection('mongodb://localhost/testB');
var modelConfig = require('./api/model/action.model');
modelConfig.dynamicModel(conn, function (model) {
model.create({name: 'testA', description: 'description A'}, function (err, data) {
console.log("data: " + data);
console.log("err: " + err);
});
});
modelConfig.dynamicModel(conn2, function (model) {
model.create({name: 'testB', description: 'description B'}, function (err, data) {
console.log("data: " + data);
console.log("err: " + err);
});
});
My model file look like bellow.
'use strict';
var restful = require("node-restful");
var mongoose = restful.mongoose;
var modelConfig = require('../schema/action.schema');
var actionSchema = new mongoose.Schema(modelConfig.schema);
module.exports.dynamicModel = function(con,cb){
var action = con.model(modelConfig.title, actionSchema);
cb(action);
};
My schema file look like bellow.
'use strict';
var restful = require("node-restful");
var mongoose = restful.mongoose;
module.exports = {
title: "action", //mongo db collection name
schema: {
name: { type: String, required: true, unique: true},
description: { type: String, required: false}
}
}
install node-restful,mongoose and mongodb package and node app
it will save the recodes in testA and testB database.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.