简体   繁体   中英

NodeJS Mongoose Connect to different MongoDB Databases and Collections

I have multiple databases with multiple collections inside my MongoDB. Below scripts work fine as my Restful API layers. I am using Mongoose to connect to the database (mongodb://localhost:3002/24hiresJobPost), and collection named "jobs". At client side, url like this http://localhost:3001/api/status ? can be sent via HTTP to get/post/put/delete data from 24hiresJobPost database. My question is how can I capture user input from android/ios client side, and connect to different databases according to user input. For example, if user wants to query data from 24hiresUser database but not 24hiresJobPost database. Currently it is not possible as the database being connected is hardcoded inside.

Server.js

//dependencies:

var express = require('express');
var mongoose = require('mongoose');
var bodyParser = require('body-parser');

//connect to mongoDB
mongoose.connect('mongodb://localhost:3002/24hiresJobPost');
mongoose.set("debug",true);

//express
var app = express();
app.use(bodyParser.urlencoded({extended:true}));
app.use(bodyParser.json());

//routes
app.use('/api', require('./routes/api'));

app.get('/test',(req,res) =>{
  console.log('/test trigger');
  res.send('server.js test OK!');
});


//strt server
app.listen(3001);
console.log('Server is runing on port 3001');

Api.js

//dependencies:
var express = require('express');
var router = express.Router();

//get models:
var Status = require('../models/status');

//routes
Status.methods(['get', 'post', 'put', 'delete']);
Status.register(router, '/status');

//return router:
module.exports = router;

Status.js

//dependencies:
var restful = require('node-restful');
var mongoose = restful.mongoose;

//Schema
var statusSchema = new mongoose.Schema({
    category : String,
    category_mostrecent_startdate : Number,
    category_mostrecent_wagesrange : Number,
    category_mostrecent_wagesrange_startdate : Number,
    category_negatedtime : Number,
    city : String,
    closed : String,
    company : String,
    date : String,
    desc : String,
    fulladdress : String,
    latitude : Number,
    longitude : Number,
    lowertitle : String,
    mostrecent_startdate : Number,
    mostrecent_wagesrange : Number,
    mostrecent_wagesrange_startdate : Number,
    negatedtime : Number,
    postimage : String,
    postkey : String,
    time : Number,
    title : String,
    uid : String,
    userimage : String,
    username : String,
    wages : String
});

//return models:
module.exports = restful.model('jobs', statusSchema);

I used this approach:

Created class Database that holds information about current DB and it loads all the associate models for given database.

const mongoose = require('mongoose');
const fs = require('fs');
const _ = require('lodash');

class Database {
    constructor(db, name) {
        this.db = db;
        this.name = name;
        this.connect(db, name);
    }

    connect(db, name) {
        const connection = mongoose.createConnection(db.init.name, db.init.options);

        fs.readdirSync(`${__dirname}/models/${name}`).forEach(function(file) {
            if (file.indexOf('.js')) {
                require(`./models/${name}/${file}`)(connection);
            }
        });

        this.connection = connection;
    }
}

module.exports = Database;

Then we had public interface for it (call it ie dbHandler.js )

const mongoose = require('mongoose');
const Database = require('./Database');
const _ = require('lodash');

mongoose.Promise = global.Promise;
const dbMap = new Map();

exports.register = (db, name = 'default') => {
    const database = new Database(db, name);
    dbMap.set(name, database);
    return database;
};

exports.mongoose = (name = 'default') => {
    return _.get(dbMap.get(name), 'connection');
};

Then you can dynamically choose different connections with ie dbHandler.mongoose('24hiresUser')

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM