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

Mongoose查询返回对象而非数组:批量更新嵌套文档报错

解决MongoError: The argument to $each in $addToSet must be an array but it was of type object

从你的日志能看到,out确实是一个包含2个元素的合法数组,但你在findOneAndUpdate的更新语句里犯了一个小语法错误:

你原本写的是:

{ $addToSet: { carCollection: { $each: { out } } } }

这里的{ out }是ES6的对象简写语法,等价于{ out: out }——这就把你的数组包装成了一个对象,而MongoDB的$each参数要求必须是数组类型,所以才会抛出这个错误。

修正后的代码

把{ out }改成直接引用out数组即可:

CarIndex.find({ '_id': { $in: ids } }, 'carID carBrand carModel location')
 .then(collections => {
  // 简化map写法,无需手动创建数组再push
  const out = collections.map(doc => {
   const {carID, carBrand, carModel, location} = doc;
   return {carID, carBrand, carModel, location};
  });
  console.log(out)
  console.log(out.length)
  console.log(typeof out)
  // 移除$each里的外层大括号,直接传入数组
  return CarCollection.findOneAndUpdate(
    { '_id': collectionId }, 
    { $addToSet: { carCollection: { $each: out } } }
  );
 });

额外优化建议

Mongoose查询返回的collections本身是文档实例数组,如果你不需要额外的字段处理,还可以用toObject()直接转成纯JS对象数组,进一步简化代码:

const out = collections.map(doc => doc.toObject({ pick: ['carID', 'carBrand', 'carModel', 'location'] }));

这样修改后,就能正确将数组元素添加到carCollection嵌套数组中,同时借助$addToSet避免重复元素的插入。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 07:07:10