0

I have in a collection an reference array of ObjectId. And I want to return the object's data linked with those Ids in the json response.

retrieveFromUser: function( req, res ) {
    var user_id =   req.params.user_id;
    User.findById( user_id, function( err, user ) {
        if( err ) {
            res.send( 404, "Unable to find user");
        } else {
            // This returns the array but I want the objects data
            return res.json( user.constructions );
        }
    });
}

How can I do that ?
thanks a lot !

2
  • If you do <code>console.log(user.constructions)</code> what is the result? Commented Oct 10, 2013 at 8:24
  • It's the array of ids: ["52556b4081b9cae812000002", etc...] Commented Oct 10, 2013 at 8:24

1 Answer 1

2

Try to use populate() method

retrieveFromUser: function( req, res ) {
 var user_id =   req.params.user_id;
    User.findOne({ _id: user_id }).populate('constructions').exec(function( err, user ) {
        if( err ) {
            res.send( 404, "Unable to find user");
        } else {
            // This returns the array but I want the objects data
            return res.json( user.constructions );
        }
    });
}
Sign up to request clarification or add additional context in comments.

5 Comments

Unfortunately, I am getting a TypeError: Cannot call method 'populate' of undefined...
@MaT, are you using mongoose? Which version of mongoose you are using?
Yes, I am using Mongoose 3.6.20. And if I use findOne, I have the undefined error.
All mongoose find methods returns Query objects mongoosejs.com/docs/api.html#query_Query (ref github.com/LearnBoost/mongoose/blob/master/lib/model.js#L880, mongoosejs.com/docs/queries.html) and findById it is just wrapper around findOne. All Query objects have populate methods, try to check it by yourself by console.log(User.findOne({ _id: user_id }))
I solved my error, this was due to a wrapped function. Thanks a lot !

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.