0

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);
    });
});

1 Answer 1

1

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 }
      )
...
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. I ended up changing the database structure instead, but I think I was using the $set wrong in the first place. I also think the schema was wrong too. It works now so I’m pleased. Thanks :)
You're welcome @norrisollie - yes, as I wrote - I think you were close, just needed to alter how you were using $set. Please mark as answer if was helpful, thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.