首页 > 解决方案 > 使用 Mongoose findOneAndUpdate() 或 updateOne() 哪个模式选择子对象?

问题描述

环境: Node.js,猫鼬

我已经寻找了几个小时的答案,但我找不到与findOneAndUpdate()updateOne()一起使用时选择子对象的模式。

我尝试了以下两种模式,但似乎都不起作用。

MyModel.findOneAndUpdate({ _id: value }, {parent: {child: 'hello world'});
MyModel.findOneAndUpdate({ _id: value }, {'parent.child': 'hello world'});

这个基本模式模式:

const MyModelSchema = new mongoose.Schema({
    parent: {
        child: {
            type: String,
            default: 'example text',
            required: true
        }
    }
});

标签: node.jsmongoose

解决方案


你想念运营商 $set

MyModel.findOneAndUpdate({ _id: value }, {$set:{'parent.child': 'hello world'}});

推荐阅读