mongoose如何只修改object的某几个value?

lwpassvoice
  • 49

大概情况和这个差不多 https://cnodejs.org/topic/50d...

schema:

const userInfoSchema = new Schema({
  uId: String,
  userId: Number,
  wxInfo: {
    unionid: String,
    openid: String,
    nickName: String,
    avatarUrl: String,
    gender: Number, 
    city: String,
    province: String,
    country: String,
    language: String, 
  },
  createTimeUtc: { type: Date, default: Date.now },
  updateTimeUtc: { type: Date, default: Date.now },
})

node:
现在是用的这样

  await UserInfoModel.findOneAndUpdate({ userId }, {
    $set: {
      'wxInfo.nickName': nickName,
      'wxInfo.avatarUrl': avatarUrl,
      'wxInfo.gender': gender,
      'wxInfo.city': city,
      'wxInfo.province': province,
      'wxInfo.country': country,
      'wxInfo.language': language,
      updateTimeUtc: Date.now(),
    }
  });

这样写会把wxInfo全部更新掉:

  UserInfoModel.findOneAndUpdate({ userId }, {
    wxInfo: {
      nickName, avatarUrl, gender, city, province, country, language,
    },
  });

怎样简单的方法写才能让nickName, avatarUrl, gender, city, province, country, language 全更新,而其他没传的保持不变?

回复
阅读 1.4k
3 个回答
UserInfoModel.findOneAndUpdate(
{
    userId
},
{
    "wxInfon.nickName" : nickName,
    "wxInfon.avatarUrl" : avatarUrl,
    "wxInfon.gender" : gender,
    "wxInfon.city" : city,
    "wxInfon.province" : province,
    "wxInfon.country" : country,
    "wxInfon.language" : language
});

你只需要把想要更新的项使用update方法就可以更新

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
你知道吗?

宣传栏