Tom Söderlund
Tom Söderlund

Reputation: 4747

Mongoose find-by-reference returns nothing

This is data from the mongo client:

> db.projects.find({ })[1];
{
    "name" : "App 276",
    "slug" : "app276",
    "createdByUser" : ObjectId("52f20518b66ae3622c000002"),
    "_id" : ObjectId("52fc91f508e3507c19000002"),
    "screens" : [ ],
    "dateUpdated" : ISODate("2014-02-13T09:34:23.102Z"),
    "dateCreated" : ISODate("2014-02-13T09:34:23.102Z"),
    "__v" : 0
}

This is my server code:

/** List Projects */
exports.list = function(req, res) {
    console.log('list', mongoose.Types.ObjectId(req.params.userId));
    return Project.find({ createdByUser: mongoose.Types.ObjectId(req.params.userId) }, function (err, projects) {
        if (!err) {
            return res.json(projects);
        }
        else {
            return res.send(err);
        }
    });
};

and this is my server output:

list 52fc9720b85bac3c1a000002
GET /api/projects 200 42ms - 2b

The JSON output is an empty array - why?

Upvotes: 2

Views: 127

Answers (2)

Feugy
Feugy

Reputation: 1918

Your requested project created by user 52f **c9720b85bac3c1a** 000002. Your database extract seems to contain a project by user 52f **20518b66ae3622c** 000002

Have you tried with the right id ?

Upvotes: 2

Artsiom Anti-Flag
Artsiom Anti-Flag

Reputation: 71

Take a look at Mongoose Population. It's better use this feature in this case. http://mongoosejs.com/docs/populate.html

Upvotes: 1

Related Questions