Home > Net >  Mongoose Error with trying to use findOneAndUpdate and update an array of objects
Mongoose Error with trying to use findOneAndUpdate and update an array of objects

Time:10-14

I'm trying to update an Array of Objects called watched_movies_list in my UserSchema using Mongoose. By utilizing the $push object given the user id by passing _id: req.body.id. However I'm getting this casting error(below) when trying to update the watched_movies_list field.

reason: CastError: Cast to ObjectId failed for value "{
    title: 'Luck',
    overview: 'Suddenly finding herself in the never-before-seen Land of Luck, the unluckiest person in the world must unite with the magical creatures there to turn her luck around.',
    poster_path: '/1HOYvwGFioUFL58UVvDRG6beEDm.jpg',
    original_title: 'Luck',
    original_language: 'en',
    id: 550,
    release_date: '2022-08-05',
    genre_ids: undefined
  }" (type Object) at path "movie_meta_data" because of "BSONTypeError"

This is my UserSchema:

  watched_movies_list: [{
    movie_meta_data: {
      type: Schema.Types.ObjectId,
      ref: "MovieDataSchema"
    },
    rating: {type: Number}
  }]

And this is the POST route:

  try {
    const user = await User.findOneAndUpdate(
      {_id: req.body.id},
      { "$push": { watched_movies_list: watchedMovie }});
    res.status(200).json({
      success: 'true',
      user: user
    })
  } catch (err) {
    res.status(400).json(err);
    throw err;
  }

CodePudding user response:

You are trying to push an "object" to your watched_movies_list array. Unfortunately this array is defined as an array of ObjectIds. You either have to first store the object in MovieDataSchema collection and then push only the _id to your array or define watched_movies_list as an array of MovieDataSchema objects (so as nested documents).

Update after feedback from comment:

In order to have nested documents you should define your schema as following:

watched_movies_list: [{
  movie: MovieDataSchema,
  rating: {type: Number}
}]

After that you should be able to make the following function call:

const user = await User.findOneAndUpdate(
      {_id: req.body.id},
      { "$push": { watched_movies_list: { movie: watchedMovie } }
);

or if you want to include your rating you should include it like this:

const user = await User.findOneAndUpdate(
      {_id: req.body.id},
      { "$push": { watched_movies_list: { movie: watchedMovie, rating: 5 } }
);
  • Related