Reputation: 37
I have problem with my code. I want to update document, which looks like this:
{
"_id": {
"$oid": "5bf2ad5a0d46b81798232cf9"
},
"manufacturer": "VW",
"model": "Golf ",
"VIN": "WVWZZZ1J212566691",
"doors": 3,
"class": "compact",
"reservations": [
{
"_id": {
"$oid": "5bf2ad5a0d46b81798232cfa"
},
"pick_up_date": {
"$date": "2014-10-13T09:13:00.000Z"
},
"drop_off_date": {
"$date": "2014-10-14T09:13:00.000Z"
},
"user_id": {
"$oid": "5bec00bdfb6fc005dcd5423b"
}
}
],
"createdAt": {
"$date": "2018-11-19T12:32:26.665Z"
},
"updatedAt": {
"$date": "2018-11-19T12:32:26.665Z"
},
"__v": 0
}
I want to add new reservation to array Reservations. My function:
const createReservationForCarId = ({ body , params }, res, next) =>
Carmodel.findById(params.id)
.then(notFound(res))
.then((carmodel) => carmodel ? Object.assign(carmodel, body).save() : null)
.then((carmodel) => carmodel ? carmodel.view(true) : null)
.then(success(res))
.catch(next)
But when I'm trying to update through:
router.put('/:id/reservation',
createReservationForCarId)
Body:
{
"reservations":[
{
"pick_up_date" : "October 13, 2017 11:13:00",
"drop_off_date": "October 14, 2017 11:13:00",
"user_id":"5bec00bdfb6fc005dcd5423b"
}
]
}
Mongo instead of update my old document is creating new one with only one reservation gave in above body.
What should I do to only update existing document, not creating new one?
Upvotes: 1
Views: 117
Reputation: 983
I suggest you use $push operator of Mongoose which will append your object to the existing array and it will not create a new one.
Check out this link:- https://github.com/Automattic/mongoose/issues/4338
Upvotes: 2
Reputation: 11
I haven't used mongoose but they have documentation for array manipulation.
See here: https://mongoosejs.com/docs/api.html#mongoosearray_MongooseArray-push
Also here is the related mongo doc for array manipulation: https://docs.mongodb.com/manual/reference/operator/update/push/
Upvotes: 0
Reputation: 156
You can try the findAndModify instead of findById in your code. Check out the syntax here
Upvotes: 0