Node JS如何更新内部元素 [英] Node JS how to update inner-inner elements

查看:61
本文介绍了Node JS如何更新内部元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用mongo和nodejs,并且试图将response对象添加到question对象

I'm working with mongo and nodejs and I'm trying to add a response object to a question object

这是我正在使用的模型的一部分:

Here's the part of the model I'm working with:

questions: [
    {
        name: String,
        responses: [
            {
                username: String,
                reply: String
            }
        ]
    }
]

我正在尝试像这样推送"对responses的响应:

I'm trying to "push" a response to the responses like so:

for(var i = 0; i < req.body.response.length && i < survey.questions.length; i++) {
    var response = req.body.response[i];

    if(response.trim() == "") continue;

    // survey.questions[i].responses.push({
    var responseIndex = "questions[" + i + "].responses"; 
    Survey.findByIdAndUpdate(survey._id, {
        "$addToSet" : { responseIndex : {
            username: (req.user ? req.user.username : null),
            reply: response
        } }
    }, function(error, survey) {
        if(error) {
            console.log(error);
        }
        console.log(survey);
    });
}

但是,问题在于它创建了一个没有数据的新问题对象.任何见识将不胜感激!

However, the problem is that it creates a new question object with no data. Any insight would be appreciated!

这是整个调查模型

/// <reference path="../../typings/tsd.d.ts" />

var mongoose = require("mongoose");

var schema = new mongoose.Schema({
    surveyName: String,
    creator: String,
    created: {
        type: Date,
        default: Date.now
    },
    questions: [
        {
            name: String,
            responses: [
                {
                    username: String,
                    reply: String
                }
            ]
        }
    ]
});

module.exports = mongoose.model('Survey', schema);
// exports.Survey = mongoose.model('Survey', schema);

推荐答案

当需要在数组内添加对象时,应使用子文档在您的question模型中. 对于您的情况,内在,也许您可​​以这样做:

When you need to add an object inside of array, you should use the $push function, because you have a subdocument inside your question model. In your case, inner-inner, probably you can do this:

Survey.findById(survey._id, function(error, res) {
    for(var i = 0; i < req.body.response.length && i < survey.questions.length; i++) {
        var response = req.body.response[i];
        if(response.trim() == "") continue;
        (res.questions[i]).responses.push(response);
    }
    res.save(function(error, res) {
        //  survey updated with responses.
    }
}

让我知道这是否可行.

这篇关于Node JS如何更新内部元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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