Home > Software engineering >  Struggle with mongoose query, pushing different Objects into different arrays in a single deeply nes
Struggle with mongoose query, pushing different Objects into different arrays in a single deeply nes

Time:03-01

I just can't figure out the query and even if it's allowed to write a single query to push 4 different objects into 4 different arrays deeply nested inside the user Object.

I receive PATCH request from front-end which's body looks like this:

{
  bodyweight: 80,
  waist: 60,
  biceps: 20,
  benchpress: 50,
  timestamp: 1645996168125
}

I want to create 4 Objects and push them into user's data in Mongo Atlas

{date:1645996168125, value:80} into user.stats.bodyweight <-array

{date:1645996168125, value:60} into user.stats.waist <-array

...etc

I am trying to figure out second argument for:

let user = await User.findOneAndUpdate({id:req.params.id}, ???)

But i am happy to update it with any other mongoose method if possible.

PS: I am not using _id given by mongoDB on purpose

CodePudding user response:

try this:

await User.findOneAndUpdate(
     {id:req.params.id},
     {$addToSet:
          {"stats.bodyweight":{date:1645996168125, value:80} } 
     }
                           )

CodePudding user response:

You'll want to use the $push operator. It accepts paths as the field names, so you can specify a path to each of the arrays.

I assume the fields included in your request are fixed (the same four property names / arrays for every request)

let user = await User.findOneAndUpdate(
  { id: req.params.id },
  {
    $push: {
      "stats.bodyweight": {
        date: 1645996168125,
        value: 80,
      },
      "stats.waist": {
        date: 1645996168125,
        value: 60,
      },
      // ...
    },
  }
);

If the fields are dynamic, use an object and if conditions, like this:

const update = {};
if ("bodyweight" in req.body) {
  update["stats.bodyweight"] = {
    date: 1645996168125,
    value: 80,
  };
}
// ...

let user = await User.findOneAndUpdate(
  { id: req.params.id },
  {
    $push: update,
  }
);

The if condition is just to demonstrate the principle, you'll probably want to use stricter type checking / validation.

  • Related