在模块化节点应用程序中创建多个Mongoose DB

时间:2016-08-09 21:05:15

标签: javascript node.js mongodb

我正在创建一个使用两个数据库的节点应用程序。 我正在尝试实现mongoose.createConnection()方法。我可以看到它如何应用于一个没有严格模块化的项目,但是当模块化这个方法没有正确调用时。

例如,如果我将所有逻辑保存在一个文件中,下面的代码很好地使用了createConnection方法:

var conn      = mongoose.createConnection('mongodb://localhost/testA');
var conn2     = mongoose.createConnection('mongodb://localhost/testB');

// stored in 'testA' database
var ModelA    = conn.model('Model', new mongoose.Schema({
title : { type : String, default : 'model in testA database' }
}));

// stored in 'testB' database
var ModelB    = conn2.model('Model', new mongoose.Schema({
title : { type : String, default : 'model in testB database' }
}));

由于严格的模块化实践,我的文件设置如下:

  

mongoose.js

var mongoose = require('mongoose');
var fs = require('fs');

// connect to the database
var conn = mongoose.createConnection('mongodb://localhost/testA');
var conn2 = mongoose.createConnection('mongodb://localhost/testB');

// traditional way of making a single Mongo connection
// mongoose.connect('mongodb://localhost/surgeon_solutions');

// specify the path to all of the models
var models_path = __dirname + '/../models'

// read all of the files in the models_path and for each one check if it is a javascript file before requiring it
fs.readdirSync(models_path).forEach(function(file) {
    if(file.indexOf('.js') > 0) {
    require(models_path + '/' + file);
    }
})
  

user_model.js

我已尝试更换' mongoose.model(' User',UserSchema);'与' conn.model(' User',UserSchema);'但这仍然行不通。

var mongoose = require('mongoose');
var crypto = require('crypto');
var jwt = require('jsonwebtoken');
var secret = "secret"

var UserSchema = new mongoose.Schema({
    username: {type: String, lowercase: true, unique: true},
    email: {type: String, lowercase: true, unique: true},
    hash: String,
    salt: String
});

UserSchema.methods.setPassword = function(password){
    this.salt = crypto.randomBytes(16).toString('hex');

    this.hash = crypto.pbkdf2Sync(password, this.salt, 1000, 64).toString('hex');
};

UserSchema.methods.validPassword = function(password) {
    var hash = crypto.pbkdf2Sync(password, this.salt, 1000, 64).toString('hex');

    return this.hash === hash;
};

UserSchema.methods.generateJWT = function() {
    var today = new Date();
    var exp = new Date(today);
    exp.setDate(today.getDate() + 1);

return jwt.sign({
    _id: this._id,
    username: this.username,
    exp: parseInt(exp.getTime() / 1000),
}, secret);
};

mongoose.model('User', UserSchema);
  

user_controller.js

var crypto = require('crypto');
var mongoose = require('mongoose'),
User = mongoose.model('User');
var passport = require('passport');
var jwt = require('express-jwt');
var secret = 'secret';
var auth = jwt({secret: secret, userProperty: 'payload'});

module.exports = {
    Register: function(req, res, next){
        if(!req.body.username || !req.body.password){
            return res.status(400).json({message: 'Please fill out all fields'});
    }
    User.findOne({username: req.body.username}, function(err, user){
        console.log('searching...')
        if(err){
            // console.log(err)
            return res.json({error: 'This username already exists.'})
        } else {
            var user = new User();
            console.log(req.body.email)
            user.username = req.body.username;
            user.setPassword(req.body.password);
            user.email = (req.body.email);
            user.save(function (err){
                if(err){ 
                    console.log(err)
                    return next(err);
                }
            return res.json({token: user.generateJWT()})
            })
        }
    })
},
  

申请结构

-Root Folder/
--Client/
---angular/
---partials/
---static/
---index.html
--node_modules/
--passport/
---passport.js
--server/
---config/
----mongoose.js
----routes.js
---controllers/
----user_controller.js
---models/
----user_model.js
--packages.json
--server.js

1 个答案:

答案 0 :(得分:2)

我认为您忘记导出class Vehicle < ActiveRecord::Base def get_history(start_time, end_time) return gsm_get_history(start_time, end_time) if communication_channel == :gsm #... end def gsm_get_history(start_time, end_time) #... end end

替换:

User model

mongoose.model('User', UserSchema);

使用多重连接:

而不是var User = mongoose.model('User', UserSchema); module.exports = User; ,您需要使用mongoose.model

替换:

conn.model

<强>与

User = mongoose.model('User');

并且不要忘记在同一个文件中定义User = conn.model('User');

conn