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

时间:2018-06-18 10:57:53

标签: node.js mongodb mongoose

我的MongoDB中有多个包含多个集合的数据库。下面的脚本可以作为我的Restful API层工作。我使用Mongoose连接到数据库(mongodb:// localhost:3002 / 24hiresJobPost),以及名为" jobs"的集合。在客户端,网址如http://localhost:3001/api/status?可以通过HTTP发送来从24hiresJobPost数据库获取/发布/放置/删除数据。我的问题是如何从android / ios客户端捕获用户输入,并根据用户输入连接到不同的数据库。例如,如果用户想要从24hiresUser数据库而不是24hiresJobPost数据库查询数据。目前,由于连接的数据库是内部硬编码的,因此无法实现。

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);

1 个答案:

答案 0 :(得分:0)

我使用了这种方法:

创建的类数据库,用于保存有关当前数据库的信息,并加载给定数据库的所有关联模型。

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;

然后我们有了它的公共接口(称之为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');
};

然后,您可以使用dbHandler.mongoose('24hiresUser')

动态选择不同的连接