使用Mongoose的$push与$each向数组追加对象返回null问题求助
解决Mongoose中$push结合$each更新数组字段返回null且无数据库变更的问题
问题场景
需要将数组中的每个对象单独添加到Mongoose模型的数组字段中,使用$push搭配$each修饰符后,返回结果为null且数据库无任何更新。已知查询条件identifier在不使用$each时可正常工作,且因需要支持重复对象,无法使用$addToSet。
尝试的代码
let identifier={customer:{external_id:'12345'}} let array = [{value:30},{value:30}] User.findOneAndUpdate(identifier,{$push:{points:{$each:array}}},{new:true}) .then((result)=>{ console.log(result) })
解决方案
1. 确保调用exec()执行查询
Mongoose的findOneAndUpdate返回的是Query对象,部分版本中直接链式调用.then()可能无法正确触发执行逻辑,添加.exec()可确保Promise正常处理:
let identifier={customer:{external_id:'12345'}} let array = [{value:30},{value:30}] User.findOneAndUpdate(identifier, {$push:{points:{$each:array}}}, {new:true}) .exec() .then((result)=>{ console.log(result) }) .catch(err => { console.error('更新出错:', err) })
2. 检查模型Schema中points字段的定义
确认points字段在User模型的Schema中被正确定义为数组类型,示例如下:
const mongoose = require('mongoose') const userSchema = new mongoose.Schema({ customer: { external_id: String }, points: [{ value: Number }] // 需明确为数组结构,匹配要插入的对象格式 }) const User = mongoose.model('User', userSchema)
3. 启用验证器(可选)
如果Schema中对points字段有验证规则,需在更新选项中添加runValidators: true,确保更新操作符合Schema约束:
User.findOneAndUpdate( identifier, {$push:{points:{$each:array}}}, {new:true, runValidators: true} // 添加runValidators选项 ) .exec() .then(result => console.log(result)) .catch(err => console.error(err))
内容的提问来源于stack exchange,提问作者Luckyfield
相关产品推荐
相关产品推荐

