Martin
Martin

Reputation: 12215

Why my mongdb $lookup does not work?

I'm trying to make a $lookup between two collections, on _id field. It always return me an empty object.

It's the exact same problem as Mongodb $lookup Not working with _id

But I already implemented his solution. It know about type coertion and my id fields are the exact same type: Schema.ObjectId

Here's my session collection:

var sessionSchema = new Schema({
    user        : { type: mongoose.Schema.ObjectId, ref: 'User' },
    startDate   : Date,
    endDate     : Date
});

and the request:

db.sessions.aggregate([{$project: {user:1}}, { $lookup : { from: "User", localField: "user", foreignField: "_id", as: "u" }} ]);

and the results:

{ "_id" : ObjectId("5697d6c810ad24b91b130df2"), "user" : ObjectId("5697d6c210ad24b91b130df1"), "u" : [ ] }
{ "_id" : ObjectId("5697d6d810ad24b91b130df3"), "user" : ObjectId("5697d6c210ad24b91b130df1"), "u" : [ ] }
{ "_id" : ObjectId("5697d70410ad24b91b130df4"), "user" : ObjectId("5697d6c210ad24b91b130df1"), "u" : [ ] }
{ "_id" : ObjectId("5697d71310ad24b91b130df5"), "user" : ObjectId("5697d6c210ad24b91b130df1"), "u" : [ ] }
{ "_id" : ObjectId("5697d71c10ad24b91b130df6"), "user" : ObjectId("5697d6c210ad24b91b130df1"), "u" : [ ] }

I don't think it could be useful to mention my User collection, because only only interesting field is _id

There must be missing an obvious thing, and because i'm not a mongo expert, I can't find it.

Upvotes: 0

Views: 903

Answers (1)

Martin
Martin

Reputation: 12215

I didn't mention i'm using Mongoose.

When you're creating a collection, Mongoose automagically create the relative table with the plural mode.

So my mistake was to reference from: "user" instead of from: "users"

Upvotes: 1

Related Questions