1

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);
            });

        });
    }

My schemas:

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]
});
4

1 回答 1

6

push返回数组的新长度responses,所以你想做这样的事情:

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]);
});
于 2013-02-06T01:52:16.103 回答