user3221132
user3221132

Reputation:

Why cant I add an array as a member to my object

For my express/mongo/mongoose router Im trying to append a object to another object before I send it. Unfortunately it never does. Where am I mistaken?

Worth noting response_study is an array of objects, if that matters.

Also the response_study is not null.

apiRouter.route('/compounds/:_id')

    .get(function(req, res) {
        Compound.findById(req.params._id, function(err, compound) {
            if (err) res.send(err);

            Study.find({compound_id: compound._id}, function( err, response_study){
               if (err) res.send(err);

               compound["studies"] = response_study;
               console.log(compound);  //logs compound without studies parameter

               res.json(compound);
           });
       });
   })

Upvotes: 2

Views: 50

Answers (1)

Rob M.
Rob M.

Reputation: 36511

Looks like you are using Mongoose? If so they don't return plain objects but MongooseDocument objects. You need to convert the MongooseDocument to a plain object before you alter it or your changes won't have any effect:

var response = compound.toObject();
response.studies = response_study;
res.json(response);

http://mongoosejs.com/docs/api.html#document_Document-toObject

It's been a while since I used mongoose, so it might be toJSON instead

Upvotes: 1

Related Questions