2

My node.js application has one MongoDB (db1) which has user details. Each user has different database (MongoDB). So I maintain all the database information in db1.

Here my question is based on user: I need to open user database connection at runtime and perform some operation in user database.

How can I do so?

1 Answer 1

2

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 below:

'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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.