Javascript Node JS如何更新内部元素

Javascript Node JS如何更新内部元素,javascript,node.js,mongoose,Javascript,Node.js,Mongoose,我正在使用mongo和nodejs,我正在尝试将响应对象添加到问题对象 以下是我正在使用的模型的一部分: questions: [ { name: String, responses: [ { username: String, reply: String } ] } ] 我正试图“推”一个对响应的响应,如下所示: fo

我正在使用mongo和nodejs,我正在尝试将
响应
对象添加到
问题
对象

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

questions: [
    {
        name: String,
        responses: [
            {
                username: String,
                reply: String
            }
        ]
    }
]
我正试图“推”一个对
响应的响应,如下所示:

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);
    });
}
for(变量i=0;i
然而,问题是它创建了一个没有数据的新问题对象。任何洞察都将不胜感激

编辑:这是整个调查模型

/// <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);
//
var mongoose=要求(“mongoose”);
var schema=newmongoose.schema({
surveyName:String,
创造者:字符串,
创建:{
类型:日期,
默认值:Date.now
},
问题:[
{
名称:String,
答复:[
{
用户名:String,
答复:String
}
]
}
]
});
module.exports=mongoose.model('Survey',schema);
//exports.Survey=mongoose.model('Survey',schema);

当您需要在数组中添加对象时,您应该使用该函数,因为在
模型中有一个问题。
在你的情况下,也许你可以这样做:

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.
    }
}
Survey.findById(Survey.\u id,函数(error,res){
对于(变量i=0;i

让我知道这是否有效。

您使用的是mongoose.js吗?我使用的是“mongoose”:“^4.4.10”jsonIs
Survey
question
模型的一个实例?
question
是调查对象模型的一个元素。嗯,我回答说
Survey
是一个
question
实例。也许我的代码不起作用,但总的想法是,你应该使用mongoose$推送功能。效果很好!谢谢!:)