Javascript 设置Mongoose集合名称

Javascript 设置Mongoose集合名称,javascript,node.js,mongodb,mongoose,mongoose-schema,Javascript,Node.js,Mongodb,Mongoose,Mongoose Schema,我被这个弄得头昏脑胀。我想将集合名称传递给Mongoose模式对象实例的模型构造函数 let mongoose = require('mongoose'), Schema = mongoose.Schema; let schema = new Schema({ name: {type: String} }, { collection: 'testing' }); module.exports = mongoose.model("Item", schema); 我可以使用如上

我被这个弄得头昏脑胀。我想将集合名称传递给Mongoose模式对象实例的模型构造函数

let mongoose = require('mongoose'),
    Schema = mongoose.Schema;

let schema = new Schema({
    name: {type: String}
}, { collection: 'testing' });

module.exports = mongoose.model("Item", schema);
我可以使用如上所示的collection参数将其从items更改为testing。我还尝试通过对象上的方法设置属性。它设置正确,如预保存挂钩中所示。但实例仍然使用原始集合名称。我想从调用代码传入集合名称

let schema = require(path.join(__rel__, __models__, "schema"));
let item = new schema(itemObject);
    item.save(function(err, item) {});

我想通过某种方式为要存储的对象传入新集合名称。

我已将架构修改为:

module.exports = function(collectionName) {
    return mongoose.model("Item", ItemSchema, collectionName);
};
把它叫做:

Item = require(path.join(__rel__, __models__, "ItemSchema")) 
("the_collection_name")

这很好。

我声明的模式如下

    const mongoose = require('mongoose');
    const Schema = mongoose.Schema;
    const marksSchema = new Schema({
      username: String,
      year: Number,
      section: String,
      week: Number,
      marks: [{
        qid: String,
        questionName: String,
        marksScored: Number,
        isAttempted: Boolean
      }],
      quizmarks:Number,
    });

    module.exports = mongoose.model('marks', marksSchema, 'marks');
并在server.js中引用如下

const Marks = require('../models/Marks');
models是包含我的所有架构的文件夹,它是my server.js之外的一个目录

const Marks = require('../models/Marks');