【问题标题】:How do I update a sub-document in MongoDB without querying the parent?如何在不查询父文档的情况下更新 MongoDB 中的子文档?
【发布时间】:2020-10-18 22:21:15
【问题描述】:

我有以下 MongoDB 架构:

let ChannelSchema = new Schema({
  name: {type: String},
  active: { type: Boolean, default: true },
}, { timestamps: true })

let UserSchema = new Schema({
  username: {type: String, required: [true, "username_required"], unique: true},
  channel: [ ChannelSchema ]
}, { timestamps: true });

我正在尝试创建一个端点来切换我的 Channel 架构的活动状态。但是,当我创建以下测试代码时,响应是 undefined

router.post('/deactivate', async (req, res, next) => {
  let channelId = req.body.channelId;
  let channel = await Channel.findOneById(channelId});
  res.json(channel);
});

在这种情况下,如何通过 id 选择频道并将活动状态更改为 false?我宁愿不必先选择用户文档。这可能吗?

【问题讨论】:

  • 您可以将 $set 用于哈希字段,将位置更新运算符用于数组字段。
  • 我得调查一下,你

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


【解决方案1】:

如果你使用 mongoose 作为 ORM,你应该使用 findById 而不是 findOneById

let channel = await Channel.findById(channelId});

【讨论】:

  • 谢谢。我实际上很快就把这个样本放在一起,实际上一直在使用 findById
【解决方案2】:

这就是最终对我有用的东西:

router.post('/deactivate', async (req, res, next) => {
  let channelId = req.body.channelId;
  let channel = await User.findOneAndUpdate({'channel._id': channelId}, { 'channel.$': 1 });
  res.json(channel);
});

我会解释它,但我不完全理解它为什么起作用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-29
    • 1970-01-01
    • 2023-04-04
    相关资源
    最近更新 更多