0

I have Locations collection in MongoDB that includes two documents. Each one of them has its own array of confirmed bookings as objects with Ids. How can I update the object that has _id: c1? Is it possible to do that in a single query?


[{
_id :63233022222222,
title :"Ravenholm",
price: 180,
capacity: 2,
confirmedBookings: [
 {
 _id : r1,
 start: 1663207200000,
 finish: 1663210799999
 },
 {
 _id: r2,
 start: 1663322400000,
 finish: 1663329599999
 }
]
},
{
_id :6323301111111111,
title :"City 17",
price: 360,
capacity: 4,
confirmedBookings: [
 {
 _id : c1,
 start: 1663207200000,
 finish: 1663210799999
 },
 {
 _id: c2,
 start: 1663322400000,
 finish: 1663329599999
 }
]
}]
danronmoon
3,8735 gold badges36 silver badges58 bronze badges
asked Sep 16, 2022 at 12:36

2 Answers 2

1

You should be able to query and update the specific object with:

const updated = await Model.findOneAndUpdate(
 { 'confirmedBookings._id': c1 },
 {
 'confirmedBookings.$.start': 'new-start',
 'confirmedBookings.$.finish': 'new-finish',
 },
 { new: true }
);
answered Sep 16, 2022 at 12:49
Sign up to request clarification or add additional context in comments.

Comments

1

You can use elemMatch to find the elements inside an array, and then update its value.

return await documentName.findOneAndUpdate(
 { 
 confirmedBookings: { $elemMatch: { _id: "c1"} } 
 }, 
 {
 "confirmedBookings.$": newValue
 }
);

Write your schema's name instead of documentName. The newValue should be the object of the new value you want to update.

Hope, it's helpful and clear

answered Sep 16, 2022 at 12:48

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.