简体   繁体   English

更新猫鼬记录内数组内的值

[英]Update value inside a array inside a mongoose record

User Schema:用户架构:

var userSchema = new mongoose.Schema({
    user: String,
    data: [{}]
});

In the schema above, I am adding question and option(MCQ) user marked inside the data array.在上面的架构中,我添加了在data数组中标记的问题和选项(MCQ)用户。 I can add new answers successfully but can't update already answered question with different options.我可以成功添加新答案,但无法使用不同选项更新已回答的问题。

Server side code:服务器端代码:

let user = await User.findOne({ user: req.body.user });
let checkUser = user.data.filter(res => res.quesId == req.body.id);
if (checkUser.length) {
    // Logic for updating
} else {
    await user.data.push({
        quesId: req.body.id,
        option: req.body.opt
    });
    user.save();
}

So what I want to do is that if the user answered the same question(determined by req.body.id ) with different option( req.body.opt ), it should be updated in the already existing record.所以我想要做的是,如果用户用不同的选项( req.body.opt )回答了相同的问题(由req.body.id确定),它应该在已经存在的记录中更新。

To update an object inside an array, you need to remove the original object then create a new one with the new data included.要更新数组内的对象,您需要删除原始对象,然后创建一个包含新数据的新对象。

Example:例子:

// Define required variables
let user = await User.findOne({ user: req.body.user });
let data = user.data;
let checkUser = data.filter(res => res.quesId == req.body.id);

// If the question already exists
if (checkUser.length > 0) {
    // Loop through the questions that already exist
    checkUser.forEach(question => {
        // Remove the question from the users data
        data.splice(data.indexOf(question), 1);
        // Append the new data onto the array
        data.push({
            quesId: req.body.id,
            option: req.body.opt
        });
        // Save the new data
        user.data = data;
        user.save();
    });
} else {
    // If the question doesn't already exist, create it
    (user.data).push({
        quesId: req.body.id,
        option: req.body.opt
    });
    // Save the changed data
    user.save();
}

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

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