【问题标题】:Mongoose- How can I create a collection with the default values?Mongoose-如何创建具有默认值的集合?
【发布时间】:2023-03-28 21:21:01
【问题描述】:

我正在使用以下代码创建架构;

var Repository = require('./base/Repository'); 
var Connection = require('./base/Connection');

    var scm = Repository.schema({
        userId : String,
        text: String,
        date: Number });

    scm.index({date:1}); scm.index({userId:1});

    var repo = Repository.create('Feedback', scm, Connection);

    module.exports = new repo();

但我想在创建此架构时为字段提供默认值。例如,我想要这样的东西;

var scm = Repository.schema({
        userId : 12334455,
        text: hello world,
        date: 19.04.2018 });

如何使用 Mongoose 进行管理?

【问题讨论】:

    标签: node.js mongodb mongoose mongoose-schema


    【解决方案1】:

    您始终可以在定义架构时指定默认值。喜欢

    Repository.schema({
    userId : { type: String, default: '12334455' },
    text: { type: String, default: 'Xyx' },
    date: { type: String, default: 12334455 }
    })
    

    这里是documentation

    【讨论】:

    • 感谢您的回答。我根据您的回答更新了架构。但是我的收藏中没有文档。我正在等待包含 userid=1234 text=yyyyy 的文档。可能是什么问题?
    • 在创建模式时,我使用以下代码; var repo = Repository.create('Feedback', scm, Connection);如何强制使用默认值创建文档
    • 您可能没有阅读文档。请在这里查看mongoosejs.com/docs/defaults.html
    【解决方案2】:

    试试这个: http://mongoosejs.com/docs/defaults.html

    您可能希望使用setDefaultsOnInsert 选项。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-05-29
      • 2022-01-07
      • 2013-11-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多