猫鼬:如何更新子嵌入式文档数组?

时间:2020-02-23 06:45:00

标签: mongoose mongoose-schema mongoose-populate

这是我的模式

const NetworkSchema = new Schema({
 user: {
 type: Schema.Types.ObjectId,
 ref: 'user'
},
name: {
  type: String
},
friendrequests: [
{
  user: {
    type: Schema.Types.ObjectId,
    ref: 'user'
  },
  name: {
    type: String
  },
  status: {
    type: String,
    default: 'pending'
  },
  date: {
    type: Date,
    default: Date.now
  }
}
],

});

我想使用它的_id更新子嵌入文档的friendrequest。我还是猫鼬的新手,请帮忙。谢谢

1 个答案:

答案 0 :(得分:0)

好,我设法使用updateOne更新了子嵌入文档

  const network = await Network.updateOne(
   {
     user: req.user.id,
     'friendrequests._id': req.params.friendrequest_id
   },
   {
     $set: { 'friendrequests.$.status': 'accepted' }
   }
  );

参考:MongoDB: How do I update a single subelement in an array, referenced by the index within the array?