简体   繁体   中英

NodeJS and MongoDB - Array of ObjectId how to return Objects

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 !

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM