【问题标题】:mongoose findOneAndUpdate returns updated document but doesn't update database猫鼬 findOneAndUpdate 返回更新的文档但不更新数据库
【发布时间】:2018-07-10 18:34:06
【问题描述】:

考虑以下猫鼬查询:

mongoose.model(collection).findOneAndUpdate({[fieldName]: fieldValue}, {$set:{processed:1}}, {new:true}, function(err, doc){
    console.log(doc);
    callback(err, doc);
});

这将返回具有属性 processed:1 的文档,但它不会更新 mongodb 表。

我没有在猫鼬模式上设置已处理的属性。所以架构会是这样的:

 var mongoose = require('mongoose');

module.exports = mongoose.model('collection', {
    _id:mongoose.Schema.Types.ObjectId,
    parm1:{type: String},
    parm2:{type: Number},
    parm3:{type: String, index:true}
}, 'mycollection');

我是否可以设置任何选项,使其在更新数据库记录的同时返回更新后的文档?

【问题讨论】:

    标签: node.js mongodb mongoose mongoose-schema


    【解决方案1】:

    Mongoose 只能使用架构中定义的字段更新表。因此,如果 processed 字段在 Mongoose 模式中不存在,它不会更新表。

    【讨论】:

      【解决方案2】:

      您可以在更新时设置strict 选项属性。这将覆盖架构并使您可以添加任何您想要但不在定义的架构中的属性。

      model.findOneAndUpdate(where, data, { ...options, strict: true });

      见:http://mongoosejs.com/docs/guide.html#strict

      【讨论】:

        猜你喜欢
        • 2020-11-13
        • 2022-01-22
        • 2016-05-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-07-13
        • 2016-04-08
        • 1970-01-01
        相关资源
        最近更新 更多