简体   繁体   English

NodeJS Mongoose连接到不同的MongoDB数据库和集合

[英]NodeJS Mongoose Connect to different MongoDB Databases and Collections

I have multiple databases with multiple collections inside my MongoDB. 我的MongoDB中有多个数据库,其中包含多个集合。 Below scripts work fine as my Restful API layers. 下面的脚本可以很好地用作我的Restful API层。 I am using Mongoose to connect to the database (mongodb://localhost:3002/24hiresJobPost), and collection named "jobs". 我正在使用Mongoose连接到数据库(mongodb:// localhost:3002 / 24hiresJobPost),并使用名为“ jobs”的集合。 At client side, url like this http://localhost:3001/api/status ? 在客户端,像这样的url http:// localhost:3001 / api / status吗? can be sent via HTTP to get/post/put/delete data from 24hiresJobPost database. 可以通过HTTP发送以从24hiresJobPost数据库获取/发布/放入/删除数据。 My question is how can I capture user input from android/ios client side, and connect to different databases according to user input. 我的问题是如何从android / ios客户端捕获用户输入,并根据用户输入连接到不同的数据库。 For example, if user wants to query data from 24hiresUser database but not 24hiresJobPost database. 例如,如果用户要从24hiresUser数据库而不是24hiresJobPost数据库查询数据。 Currently it is not possible as the database being connected is hardcoded inside. 当前不可能,因为所连接的数据库是内部硬编码的。

Server.js 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 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 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. 创建的类Database保存有关当前DB的信息,并为给定数据库加载所有关联模型。

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 ) 然后我们有了它的公共接口(称为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') 然后,您可以使用dbHandler.mongoose('24hiresUser')动态选择不同的连接

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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