HaakonFlaar
HaakonFlaar

Reputation: 397

Push a value to an array inside an object in mongoose schema

I am trying to push a value to an array which is inside an object in the mongoose schema. Here is my schema:

const UserSchema = new mongoose.Schema({
  username: { type: String, required: true, unique: true },
  watchlist: {
    savedMovies: { type: [String] },
    ratings: { type: [Number] },
    avgRating: { type: Number, default: null },
  },
});

I want to push a value to the savedMovies array inside the watchlist object. How can I do that? I attempted the following.

router.post("/:username/favmovie", async (req: Request, res: Response) => {
  try {
    const user = await User.find({ username: req.params.username }).lean().exec();
    const updatedUser = await User.updateOne({ _id: user[0]._id }, { watchlist: { $addToSet: { savedMovies: req.body.movieID } } });
    res.json(updatedUser);
  } catch (err) {
    res.json({ message: err });
  }
});

But it simply added a new watchlist object, which is not what I want. I only want to update the savedMovies array inside the watchlist object.

Upvotes: 0

Views: 173

Answers (1)

wak786
wak786

Reputation: 1615

Try this -

db.usersdata.update({
  "_id": 1.0
},
{
       $addToSet: { "watchlist.savedMovies": "Movies4" } 
})

Mongo Playground

Upvotes: 1

Related Questions