MLWDEV
MLWDEV

Reputation: 65

MongoDB aggregation and $lookup always returning empty array

Been struggling with this for a while can't work out why I am always getting an empty array for my loop up data.

I have data in my 'users' collection

{
  storeid: 1,
  name: 'joe bloggs'
}

I have a stores collection with the following data in

{
  _id: ObjectId(1),
  storeName: 'Store name'
}

I want to pull the storename that each user is part of when getting all users. I have a query like the below to do this:

User.aggregate([
  {
    $lookup: {
      from: "store",
      localField: "storeid",
      foreignField: "_id",
      as: "storeDetail"
    }
  }
])
.then(users => {
   res.send(users);
}).catch(err => {
  //error
});

However what I get here is 'storeDetail' always returning blank. Not too sure what I am doing wrong, I have checked that my collection names are correct as per db.getCollectionNames() from the mongo shell.

Thanks,

Upvotes: 2

Views: 1012

Answers (2)

Piyush Bansal
Piyush Bansal

Reputation: 1723

Note: You mentioned wrong schema

{
  _id: ObjectId(1),
  storeName: 'Store name'
}

Here is the solution

ObjectId(1) is wrong. ObjectId always be the hash value of 24 lengths of string.

User Collection:

{
    "_id" : ObjectId("5b8d246730739cd950b7b314"),
    "storeid" : ObjectId("5b8d249b30739cd950b7b323"),
    "name" : "joe bloggs"
}

Store Collection

{
    "_id" : ObjectId("5b8d249b30739cd950b7b323"),
    "storeName" : "Store name"
}

Mongo Query

db.getCollection('user').aggregate([
{$lookup:{from: 'store',localField: 'storeid',foreignField: '_id',as: 'stores'}},
])

Result

{
    "_id" : ObjectId("5b8d246730739cd950b7b314"),
    "storeid" : ObjectId("5b8d249b30739cd950b7b323"),
    "name" : "joe bloggs",
    "stores" : [ 
        {
            "_id" : ObjectId("5b8d249b30739cd950b7b323"),
            "storeName" : "Store name"
        }
    ]
}

Hope it helps you.

Upvotes: 1

MLWDEV
MLWDEV

Reputation: 65

Turns out I was trying to use different Schema types in localField (string) and foreignField (ObjectId). Converting the localField in the model to be of type ObjectId fixed it.

type: String,//Didn't work
type: mongoose.Schema.Types.ObjectId,//Did work

Upvotes: 2

Related Questions