在猫鼬中,我如何将子文档推送到一组保存的对象上,然后返回我刚推送的内容? [英] In mongoose how do I push a subdocument onto an array of a saved objects and then return what I just pushed?

查看:85
本文介绍了在猫鼬中,我如何将子文档推送到一组保存的对象上,然后返回我刚推送的内容?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图随时将子文档推送到我的对象上.以下是POST的处理程序.首先,它检查是否邀请该帐户参加调查.如果一切都完成了,那么我们希望将响应推送到调查响应数组中.

I am trying to push a subdocument onto my object whenever. Below is the handler for POST. First it checks whether the account was invited to take the survey. If everything checks out, then we want to push the response onto the survey responses array.

    handler: function(req, res, next) {
        var survey = req.params.survey;
        var account = req.params.account;

        Survey.findById(survey).exec(function(err, survey) {
            if(err) { return handleError(res, err); }
            if(!survey) { return handleError(res, 'Invalid Survey', true); }
            if(!account) { return handleError(res, 'Invalid Account', true); }

            var invite = _(survey.invites).find(function(i){
                return i.account == account;
            });

            if(!invite) {
                return handleError(res, 'No invite exists for user');
            }

            if(!survey.responses) {
                survey.responses = [];
            }

            var response = survey.responses.push(req.params);

            console.log(response); // returns an integer want it to return the subdocument

            survey.save(function(err){
                if(err) { return handleError(res, err); }
                return res.send(response);
            });

        });
    }

我的模式:

var SurveyResponseSchema = new Schema({
    account: {type: Schema.Types.ObjectId, ref: 'Account', required: true},
    answers: [SurveyAnswerSchema],
    complete: Boolean
});

var SurveySchema = new Schema({
    start_date: Date,
    end_date: Date,
    title: String,
    survey_questions: [SurveyQuestionSchema],
    invites: [SurveyInviteSchema],
    responses: [SurveyResponseSchema]
});

推荐答案

push返回responses数组的新长度,因此您需要执行以下操作:

push returns the new length of the responses array, so you'd want to do something like this:

var responseIx = survey.responses.push(req.params) - 1;

survey.save(function(err, survey){
    if(err) { return handleError(res, err); }
    return res.send(survey.responses[responseIx]);
});

这篇关于在猫鼬中,我如何将子文档推送到一组保存的对象上,然后返回我刚推送的内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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