mongodb:从嵌套的引用数组中拉出一项

时间:2018-12-15 14:27:09

标签: javascript node.js mongodb mongoose

我有一个嵌套的引用数组

const userSchema = new Schema(
  {
    _id: Schema.Types.ObjectId,
    name: String,
   posts: [{ type: Schema.Types.ObjectId, ref: "Post" }]
  }
);

我想从该数组中删除一个引用,我认为使用

会很容易
 User.update({ name: currentName}, { $pull: { posts: postId }});

这和

之类的变体
 User.update(
    { name: currentName},
    { $pull: { posts: mongoose.Types.ObjectId(postId) } }
  );

或使用findOneAndUpdate都不适合我。

postId的格式类似于"5c150b855999681f7423aacb"

1 个答案:

答案 0 :(得分:1)

User.findOneAndUpdate({
_id: mongoose.Types.ObjectId('YOUR_DATA_ID')
},
{ name: currentName,
{ $pull: { posts: mongoose.Types.ObjectId(postId) } }
);
相关问题