访问先前定义的模型

时间:2017-05-31 20:54:51

标签: node.js mongodb mongoose

好的,要点:我已经获得了一个node.js服务(应该是什么)以前定义的模型和模式,但我想建立一个新的MongoDB连接,以便并行化一些批量操作

app.js:

// bunch of requires
var mongoose = require('mongoose');
mongoose.Promise = require('q').Promise;

if( mongoose.connection.readyState === 0 ) {
    mongoose.connect('mongo:27017/MyDbName?connectTimeoutMS=30000', function(err) { if (err) console.log(err); }); // connect to our database
}

var app = express();
// some more stuff happens here

require('./routes/identityService')(app);

identityService.js:

require('./proc/importUserProcessor');
module.exports = function(app) {
    // Create an express router to serve our identity service.
    var router = express.Router();

    router.post('/request/import', (req, res) => {
        importProcessor.processImportFiles(req, res)
            .done(() => {
                res.sendStatus(200);
            }, err => {
                log.error('Error importing: ', err);
                res.sendStatus(599);
            });
    });

authSchema.js:

var mongoose = require('mongoose');
var Q = require("q");
mongoose.Promise = Q.Promise;

var myDB = mongoose.connection.useDb('MyDbName');

// define the schema for our user model
var userSchema = mongoose.Schema({
    // schema here
});

// create the model for users and expose it to our app
var userModel = myDB.model('Users', userSchema);

module.exports = {
    User            : userModel
};

最后是importUserProcessor.js:

const Q = require('q');
const mongoose = require('mongoose');
mongoose.Promise = Q.Promise;

const AuthSchema = require('../models/authSchema');

const processingFunc = (chunk, encoding, completeCb) => {
    let connUri = 'mongo:27017/MyDbName?connectTimeoutMS=30000';
    let dbConn = ?????
    // I've tried mongoose.createConnection(connUri) and
    // mongoose.connection.useDb('MyDbName') but
    // no matter what I've tried, it doesn't find any of the models
    // from the authSchema file

    dbConn.on('error', err=>{ //stuff });
    dbConn.once('open', () => { // tried it in this block and out } );

    let User = dbConn.model('Users'); // or 'User' or 'Userss' or 'users' or 'user'

    dbConn.close();
    completeCb();
};

const processImportFiles = (req, res) => {
    // calls some streams which call processingFunc above
};

module.exports = {
    processImportFiles: processImportFiles
};

因此,用文件命中定义的路径解析所述文件,然后将它们抛出一些流,其想法是制作" parallel"在一些处理之后调用数据库以批量插入新记录。我希望通过新的联系这样做,但没有成功。有人得到了什么?

1 个答案:

答案 0 :(得分:0)

似乎我对我正在看的example和猫鼬的documentation的情况产生了误解。文档声明:

  

模型始终作用于单个连接。

这似乎是真的。如果示例将模型直接附加到mongoose对象,我们的代码将模型专门附加到默认连接池的myDB连接。而且,即使我尝试在importUserProcessor.js中通过mongoose.connection.useDb('MyDbName')使用该连接,它在技术上仍然是一个没有注册模型的不同连接。

如果有任何错误,请有人纠正我。