norrisollie
norrisollie

Reputation: 331

Replacing previous array of objects with new array of objects using express/mongoose

I am trying to update the favourite stations array in my database, however I just can't seem to be able to update it? I have searched for ages to try and find a solution, but nothing seems to work.

I have the ID saved in the cookie, and am sending that in the body when the update request is made...

"selected" is an array of objects. this is what will need replace the contents of the to the favouriteStations property, or add it if it is empty.

the database structure is like this:

"id": id,
"email: "test@test",
"password": "test",
"userInfo": {
    "firstName": "test",
    "lastName": "test",
    "favouriteStations": [{array i want to replace}]
}

i have tried many different combinations, however this is what i have so far, and it doesnt work

app.post("/api/update", (req, res) => {
  console.log("updating user details");
  const { id, selected } = req.body;

  UserModel.findOneAndUpdate(
    { _id: id },
    { userInfo: { favouriteStations: { $set: selected } } },
    { useFindAndModify: false }
  )
    .then((user, err) => {
      if (err) {
        console.log("an error?");
        res.status(500).json({
          error: "Server error",
        });
      } else if (!user) {
        console.log("user not exists?");
        res.status(401).json({
          error: "Incorrect credentials",
        });
      } else {
        console.log("updated?");
        console.log(user);
      }
    })
    .catch((err) => {
      console.log(err);
    });
});

Upvotes: 0

Views: 159

Answers (1)

Kuyashii
Kuyashii

Reputation: 398

It is unclear as to what you mean by ".. it doesn't work", can you elaborate please i.e. what errors do you receive? If none, what does happen?

The $set operator should be used in the following form, from MongoDB docs:

{ $set: { <field1>: <value1>, ... } }

In saying that, you may not be accessing favouriteStations correctly, use dot-notation to access the subdocument as follows:

...
    UserModel.findOneAndUpdate(
        { _id: id },
        { $set: {'userInfo.favouriteStations': selected} } ,
        { useFindAndModify: false }
      )
...

Upvotes: 1

Related Questions