且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在嵌套猫鼬模式中将输入数组保存到子模式?

更新时间:2023-02-21 12:17:00

您可以使用原子更新方法,例如 findOneAndUpdate() 插入单个文档.在这里,您还可以使用本机 $push 操作符进行推送新的问题和问题数组的答案,而不是在可以让mongo完成服务器上的所有工作时使用循环.

You can use an atomic update method like findOneAndUpdate() for your post where you can specify the upsert option. If upsert is true and no document matches the query criteria, findOneAndUpdate() inserts a single document. Here that's where you can also use the native $push operator to push the new question and answers to the question array, rather than using a loop when you can let mongo do all the work on the server.

以下示例显示了如何重构代码:

The following example shows how you can refactor your code:

var express = require('express');
var router = express.Router();
var Survey = require('../models/QBank');

router.post('/', function(req, res, next){ 
    Survey.findOneAndUpdate(
        { "surveyname": req.body.sname }, /* <query> */
        { /* <update> */
            "$push": {
                "question": {
                    "que": req.body.que,
                    "ans1": req.body.ans1,
                    "ans2": req.body.ans2,
                    "ans3": req.body.ans3,
                    "ans4": req.body.ans4
                }
            } 
        },
        { "upsert": true }, /* <options> */
        function(err, doc){ /* <callback> */
            if(err) res.json(err);
            else
                req.flash('success_msg', 'Question saved to QBank');  
            res.redirect("/CreateSurvey");
        }
    );
});

module.exports = router;

在上面,如果<update>参数包含更新运算符表达式,则会创建<query><update>参数的字段和值.更新通过<query>参数中的相等子句创建基础文档,然后应用<update>参数中的更新表达式.

In the above, the fields and values of both the <query> and <update> parameters are created if the <update> parameter contains update operator expressions. The update creates a base document from the equality clauses in the <query> parameter, and then applies the update expressions from the <update> parameter.