Home > database >  Mongoose Update different types of records
Mongoose Update different types of records

Time:08-25

I tried to update objects with array on mongoose. but its not working as exprected.

I want to update email and "first" and "last" names also price array push new object

{
  "email": "[email protected]",
  "firstName": "Test",
  "lastName": "T",
  "prices": [
    {
      "date": "2022-08-24T07:29:01.639Z",
      "price": 45
    }
  ]
}

my update function

const entity = await User.findByIdAndUpdate(id, request.payload, {
                new: true,
                runValidators: true,
                context: "query",
            }).exec();

i want to update like this. prices array we need to push and update the email,first & last name as well

{
  "email": "[email protected]",
  "firstName": "Test",
  "lastName": "T",
  "prices": [
    {
      "date": "2022-08-24T07:29:01.639Z",
      "price": 45
    },
    {
      "date": "2022-07-24T09:29:01.639Z",
      "price": 55
    }
  ]
}

CodePudding user response:

You need to split your payload into 2 operations inside the update object: $set and $push

User.findByIdAndUpdate(id, {
    $set: {
        email: request.payload.email,
        firstName: request.payload.firstName,
        lastName: request.payload.lastName
    },
    $push: {
        prices: {
            $each: request.payload.prices 
        }
    }
}, {
    new: true,
    runValidators: true,
    context: "query",
})
  • Related