【问题标题】:Setting Mongoose collection name设置 Mongoose 集合名称
【发布时间】:2018-12-05 05:51:41
【问题描述】:

这让我很头疼。我想将集合名称传递给 Mongoose Schema 对象实例的模型构造函数。

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

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

module.exports = mongoose.model("Item", schema);

我可以使用上面提到的集合参数将它从项目更改为测试。我还尝试通过对象上的方法设置属性。它正确设置它,如在预保存挂钩中看到的那样。但该实例仍使用原始集合名称。我想从调用代码中传入一个集合名称。

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

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

【问题讨论】:

    标签: javascript node.js mongodb mongoose mongoose-schema


    【解决方案1】:

    我已将架构修改为:

    module.exports = function(collectionName) {
        return mongoose.model("Item", ItemSchema, collectionName);
    };
    

    然后这样称呼它:

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

    效果很好。

    【讨论】:

      【解决方案2】:

      我声明了如下所示的架构

          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 是包含我所有架构的文件夹,它是我 server.js 之外的一个目录

      【讨论】:

        猜你喜欢
        • 2020-08-06
        • 2011-11-21
        • 2014-09-22
        • 2013-07-22
        • 2015-05-21
        • 2021-07-29
        • 1970-01-01
        • 1970-01-01
        • 2011-04-05
        相关资源
        最近更新 更多