0

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"

1 Answer 1

1
User.findOneAndUpdate({
_id: mongoose.Types.ObjectId('YOUR_DATA_ID')
},
{ name: currentName,
{ $pull: { posts: mongoose.Types.ObjectId(postId) } }
);
Sign up to request clarification or add additional context in comments.

2 Comments

why did you put the id: mongoose.Types.ObjectId('YOUR_DATA_ID') there? It worked without it for me.
name is not an unique one. if you use findOneAndUpdate, need to find an unique value in records.So I use to findOne with _id and Update the records

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.