猫鼬查找和更新删除其他字段 [英] mongoose find and update removes the other fields

查看:53
本文介绍了猫鼬查找和更新删除其他字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的架构:

this.schema = new Schema({
    userEmail: String
    environments: [
        {
            envId: String,
            appPreference: String,
            language: String,
            timeZone: String,
            summaryNotificationSchedule: {
                timeOfTheDay: String
            }
        }
    ]
});

更新请求:

{
  "envId": "u2",
  "appPreference": "put2",
  "timeZone": "gmt",
  "summaryNotificationSchedule.timeOfTheDay": "32400",
}

如您所见,我没有在更新请求中发送 "language": "abc", 并且在结果中我看到 language 字段是移除.我想更新字段但不删除其他字段

As you can see, I am not sending "language": "abc", in the update request and in the result I see the language field is removed. I want to update the fields but not remove the other fields

Mongoose 查找和更新调用:

await this.model.findOneAndUpdate({ userEmail, 'environments.envId': envId }, { $set: { 'environments.$': setPreferenceFields } }, { new: true });

推荐答案

您可以先根据您的请求创建更新对象:

You can create update object from your request first:

let request = {
  "envId": "u2",
  "appPreference": "put2",
  "timeZone": "gmt",
  "summaryNotificationSchedule.timeOfTheDay": "32400",
};

let update = Object.keys(request).reduce((acc, cur) => {
  acc[`environments.$.${cur}`] = request[cur];
  return acc;
}, {})

console.log(update);

然后将其传递给更新:

await this.model.findOneAndUpdate({ userEmail, 'environments.envId': envId }, { $set: update }, { new: true });

这篇关于猫鼬查找和更新删除其他字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆