Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Web Technology by (19.9k points)

I'm using express-restify-mongoose library to have rest endpoints agaist mongoose.

I have schema looks like this:

const BookSchema = new Schema(

  {

    name: { type: String },

    items: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Book' }],

  }

);

So I send http patch request: { name: 'blabla' } and it change the name as expect.

But when I want to add item to items array like { items: ["5dd138199f6ecb3990360328"] } its replace the entire object (with one 5dd138199f6ecb399036032d item).

After I digging in the source code I see here the function uses findOneAndUpdate and $set.

So my question is there is any way to use $push or any function/property in the $set value?

I can't add to this library, but maybe there is any workaround solution here?

1 Answer

0 votes
by (25.1k points)

I think the closest solution in mongoose is to use Set Elements in Arrays:

"items.1": "5dd138199f6ecb3990360355"

Which will add to array, but you have to pass the position.

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...