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

Mongoose: How to update sub embedded document array?

这是我的架构

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。我还是猫鼬的新手请帮忙。谢谢

好的,成功使用 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?