【问题标题】:Mongoose Error with trying to use findOneAndUpdate and update an array of objectsMongoose 尝试使用 findOneAndUpdate 并更新对象数组时出错
【发布时间】:2022-10-13 14:00:01
【问题描述】:

我正在尝试使用 Mongoose 在我的 UserSchema 中更新一个名为 watched_movies_list 的对象数组。通过传递_id: req.body.id,利用给定用户ID的$push对象。但是,在尝试更新 watched_movies_list 字段时,我遇到了这个转换错误(如下)。

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"

这是我的用户架构:

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

这是 POST 路线:

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

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

    您正在尝试将“对象”推送到您的 watched_movies_list 数组。不幸的是,这个数组被定义为一个 ObjectIds 数组。您要么必须首先将对象存储在 MovieDataSchema 集合中,然后仅将 _id 推送到您的数组中,要么将 watched_movies_list 定义为 MovieDataSchema 对象的数组(如嵌套文档)。

    评论反馈后更新:

    为了拥有嵌套文档,您应该将架构定义如下:

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

    之后,您应该能够进行以下函数调用:

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

    或者如果你想包括你的评级,你应该像这样包括它:

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

    【讨论】:

    • 好吧,我想我明白了。但是,嵌套文档的正确方法是什么?目前我在我的用户文件顶部有重要的const MovieDataSchema = require('./Movie').schema; 和我的watched_movies_list 对象`[MovieDataSchema] 但这似乎也不起作用。
    • 调整了我的答案以匹配您所需的架构。
    猜你喜欢
    • 1970-01-01
    • 2018-12-16
    • 1970-01-01
    • 2020-09-01
    • 1970-01-01
    • 2022-11-01
    • 2017-08-13
    • 1970-01-01
    • 2020-05-20
    相关资源
    最近更新 更多