0
var mongoose = require('mongoose'),
Schema = mongoose.Schema;

var sensorModel = new Schema({
key: String,
value: Schema.Types.Mixed
})
modules.export = mongoose.model('collectionName',sensorModel);

我想将集合的名称从我的主 app.js 文件传递​​给它,然后在模型代码中指定它,有没有办法可以做到这一点?

4

1 回答 1

1

请尝试Template string如下

传感器模型.js

module.exports = function (modelName) { 
    // sensorModel definition...
    //...

    var str = `${modelName}`;
    mongoose.model(str, sensorModel);
});

应用程序.js

var modelName = 'collectionName';
require('./models/sensorModel.js')(modelName); // require the model file before invoking `mongoose.model`.
var CollectionName = mongoose.model('collectionName');
于 2016-02-21T15:36:39.920 回答