Casper222
Casper222

Reputation: 101

How to update nested object? Mongoose

I'm trying to update auction.auctionDescription. After the request is sent auction.auctionDescription is updated, but auction.auctionImage is deleted.

await Auction.updateOne({_id: id} ,{auction: {'auctionDescription': auctionDescription}})

My document looks like the following:

_id: ObjectId("...")
user: "..."
animal: {...}
auction: {
  auctionImage: "path/to/image.jpeg"
  auctionDescription: "..."
}

Upvotes: 0

Views: 40

Answers (1)

mhodges
mhodges

Reputation: 11116

The way you currently have it coded, you are targeting the entire auction property and replacing it with the value {"auctionDescription": auctionDescription}, which is why it's overwriting the entire existing object.

if you are just trying to update a property on an object on a document, you can use "dot notation" to target the specific property on the object you are trying to update, like so:

await Auction.updateOne({_id: id}, {"auction.auctionDescription": auctionDescription})

Upvotes: 1

Related Questions