首页 > 解决方案 > `$set` 可以替换 mongoDB 中 Boolean 类型的字段值吗?

问题描述

这是该问题的示例架构:

const sample = new Schema({
  scope: {
    type: String,
    enum: ['draft', 'published'],
    default: 'draft',
  },
  isOutOfService: {
    type: Boolean,
    default: false,
  },
});

以及模式的示例数据:

const data = {
  _id: 1,
  scope: 'draft',
  isOutOfService: false,
};

现在我想将字段scope值更新为published并将isOutOfService值更新为true.

我将下面的代码与猫鼬一起使用:

const updated = await sample.findOneAndUpdate({
  _id: 1
}, {
  $set: {
    scope: 'published',
    isOutOfService: true
  }
}, {
  new: true,
}).lean().exec();

而更新操作的结果是:

{
  _id: 1,
  scope: 'published',
  isOutOfService: false,
}

我不知道为什么scope被替换而isOutOfService没有被替换?

标签: node.jsmongodbmongoose

解决方案


推荐阅读