如何使用Mongoose更新嵌套对象?求助city_name更新失败问题
解决Mongoose更新嵌套字段city_name失败的问题
可能的问题及修复方案
1. Schema定义存在语法错误
你的Schema里有两处关键语法错误,会导致模型无法正确映射MongoDB数据,进而使更新操作失效:
mongoose.schema需改为mongoose.Schema(Mongoose的Schema构造函数首字母为大写)- 所有类型定义如
type:number需改为type:Number(JavaScript内置类型构造函数首字母为大写,String同理)
修正后的Schema:
const addressSchema = new mongoose.Schema({ address:{ door_no:{type:Number}, other_details:{ street_name:{ type: String}, city:{ city_name:{type:String}, pincode:{type:String}, } } } })
2. 异步操作未正确处理
findByIdAndUpdate是异步方法,若未用await(在异步函数中)或回调函数处理,可能操作还未执行完成就判定失败。同时建议添加{new: true, runValidators: true}选项:
new: true:返回更新后的文档,方便确认结果runValidators: true:启用Schema验证,避免不符合规则的数据被写入
修正后的更新代码(异步函数版本):
// 需在async函数内执行 const updatedAddress = await addressModel.findByIdAndUpdate( id, // findByIdAndUpdate第一个参数直接传入_id值,无需包裹对象 {$set: {'address.other_details.city.city_name': '44xd3xc'}}, {new: true, runValidators: true} ); console.log(updatedAddress); // 打印更新后的文档验证结果
3. 额外提示:Schema与实际数据字段不匹配
你的Schema中other_details下是street_name,但示例数据库数据里是street,虽然这不会影响city_name的更新,但建议保持Schema和数据库字段一致,避免后续操作出现意外问题。
内容的提问来源于stack exchange,提问作者Shanthi B
相关产品推荐
相关产品推荐

