You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

MongoDB中如何向文档内嵌数组添加元素?现有代码问题排查

问题修复方案

你的代码存在3个核心错误,按以下步骤修改即可:

问题1:查询条件类型不匹配

MongoDB文档的_id是ObjectId类型,你传入的是字符串,导致查询不到对应餐厅,更新操作直接失效。

问题2:更新返回值判断字段错误

updateOne的返回结果没有insertedCount字段,该字段仅在插入文档的API中存在,更新操作的成功判断需要使用matchedCount(匹配到的文档数)和modifiedCount(实际修改的文档数)。

问题3:操作符选择不符合需求(可选优化)

$addToSet只有当整条评论内容完全不重复时才会插入,若业务允许相同内容的评论提交,建议替换为$push。

修改后的完整代码

第一步:修改reviews.js

// 顶部引入ObjectId
const { ObjectId } = require('mongodb');
const mongoCollections = require('../config/mongoCollections');
const restaurants = mongoCollections.restaurants;

module.exports = {
  async created (restaurantId, title, reviewer, rating, dateOfReview, review) {
    // 校验并转换id格式
    if (!ObjectId.isValid(restaurantId)) throw '无效的餐厅ID格式';
    const parsedRestaurantId = ObjectId(restaurantId);

    const restaurantsCollection = await restaurants();
    let newReview = {
      restaurantId : parsedRestaurantId,
      title : title,
      reviewer : reviewer,
      rating : rating,
      dateOfReview : dateOfReview,
      review : review
    };

    const updateInfo = await restaurantsCollection.updateOne(
      {_id : parsedRestaurantId},
      // 允许重复评论就用$push,需要去重就保留$addToSet
      {$push: {reviews: newReview}}
    )
    
    // 正确的更新结果判断
    if (updateInfo.matchedCount === 0) throw '未找到对应餐厅,添加评论失败';
    if (updateInfo.modifiedCount === 0) throw '评论添加失败,未更新任何数据';
  }
}

其他文件无需修改,直接运行seed.js即可正常插入评论。


内容的提问来源于stack exchange,提问作者Swayam Shah

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 08:45:04