繁体   English   中英

猫鼬-搜索复杂的嵌套文档并更新子文档的某些字段

[英]Mongoose - search a complex nested document and update some fields of a sub-document

我试图根据邮递员req.body提供的密钥更新猫鼬子文档的某些字段。

我尝试了一些解决方案,但没有成功的结局。 我想遍历req.body并更新必要的字段。 就像我在“ //更新功能”下尝试过的一样

这是我的架构。

    _id: mongoose.Schema.Types.ObjectId,
    profile: {
        full_name: {
            first_name: String,
            last_name: String
        },
        phone: Number,
        email: String,
        gender: String,
        address: {
            city: String,
            street: String,
        },
        occupation: String,
        biography: String
    },
    password: {
        type: String,
        required: true
    },
}, {
    timestamps: {
        createdAt: 'created_at'
    }
})
module.exports = mongoose.model('Assistant', assistantSchema);

这是我要更新值的更新路线

router.patch('/:assistantId', Check_Auth, async (req, res, next) => {
    const id = req.params.assistantId;

//update function
    const updateParams = req.body;
    const set = {};
    for (const field of updateParams) {
        set['assistant.$.' + field.key] = field.value
    }

//update
    try {
        await Assistant.updateOne({
            _id: id
        }, {
            $set: set
        }).exec().then(result => {
            console.log(result);
            res.status(201).json(result)
        }).catch(err => {
            console.log(err);
            res.status(403).json({
                errmsg: "Ooh something happen, Not able to update profile try again"
            })
        })
    } catch (err) {
        res.status(500).json({
            errmsg: err
        })
    }
});

这是我邮递员的价值观

[
    {"key": "phone", "value": "651788661"},
    {"key": "email", "value": "dasimathias@gmail.com"},
    {"key": "city", "value": "douala"},
    {"key": "street", "value": "bonaberi"},
    {"key": "biography", "value": "just share a little code"}
]
```

给定要作为后期请求发送的数据,传递给$set的对象如下所示:

{ 'assistant.$.phone': '651788661',
  'assistant.$.email': 'dasimathias@gmail.com',
  'assistant.$.city': 'douala',
  'assistant.$.street': 'bonaberi',
  'assistant.$.biography': 'just share a little code' }

这与您的架构不一致,如果您尝试更新profile属性,可以这样做:

for (const field of updateParams) {
  if(field.key == "city") set[`profile.address.${field.key}`] = field.value
  else set[`profile.${field.key}`] = field.value
}

这给出了这样的对象set

{ 'profile.phone': '651788661',
  'profile.email': 'dasimathias@gmail.com',
  'profile.address.city': 'douala',
  'profile.street': 'bonaberi',
  'profile.biography': 'just share a little code' 
}

请注意, city嵌套在address内部,因此您需要访问它,您必须对full_name进行相同的操作(条件)。
如果您要更新子文档数组:

set[`assistant.$.profile.address.${field.key}`]
set[`assistant.$.profile.${field.key}`]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM