简体   繁体   中英

mongodb: pull one item from nested array of references

I have a nested array of references

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

from that array I want to remove one reference, I assumed this would be easy using

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

this and variations like

 User.update(
    { name: currentName},
    { $pull: { posts: mongoose.Types.ObjectId(postId) } }
  );

or using findOneAndUpdate all didn't work for me.

postId is formated like for example "5c150b855999681f7423aacb"

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM