Categories
JavaScript Answers

How to use Mongoose to update values in array of objects with Node.js?

Spread the love

To use Mongoose to update values in array of objects with Node.js, we use the $set operator.

For instance, we write

Person.update(
  { "items.id": 2 },
  {
    $set: {
      "items.$.name": "updated",
      "items.$.value": "two updated",
    },
  },
  (err) => {}
);

to call update with an object with $set set to an object with the fields in the item with id 2 to update.

The item being updated is the object in items with id 2.

We update the name and value fields of it.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *