Search code examples
node.jsmongodbmongoosemongoose-schemamongoose-populate

MongoDB - Mongoose with NodeJS find and join collection


I need to find and join another collection to get the businesses data from businesses collection and the profile description which is saved in the profiles collection. Latest version of nodejs and mongoose.

businesses = await Business.find({}, "business_id name industry")
      .limit(limit * 1)
      .skip((page - 1) * limit)
      .exec();

That is the code, which I need later also for the pagination.

Now I found a solution with $Lookup in Mongoose. My code looks like

Business.aggregate([{
        $lookup: {
            from: "profiles", // collection name in db
            localField: "business_id",
            foreignField: "business_id",
            as: "profile"
        }
    }]).exec(function(err, profile) {
        console.log(profile[0]);
    });

The Business and Profile is saved with the business_id in a field. So I can't work with _id from Mongoose. I never before work with mongoose and two collections.

The issue is now that the profile[0] is not connected to the correct business. So the profile is a another one as from the business find above.

I need to find the latest 10 Businesses and join to another collection and grap also the profile details. What I make wrong here, has anyone a example for this behauivor ?


Solution

  • Use https://mongoosejs.com/docs/populate.html

    As in your case you don't have ObjectId here you can use populate-virtuals

    So far you've only populated based on the _id field. However, that's sometimes not the right choice. In particular, arrays that grow without bound are a MongoDB anti-pattern. Using mongoose virtuals, you can define more sophisticated relationships between documents.

    const BusinessSchema = new Schema({
      name: String
    });
    BusinessSchema.virtual('profile', {
      ref: 'Profile', // The model to use
      localField: 'business_id', // Find people where `localField`
      foreignField: 'business_id', // is equal to `foreignField`
      // If `justOne` is true, 'members' will be a single doc as opposed to
      // an array. `justOne` is false by default.
      justOne: false,
      options: { sort: { name: -1 }, limit: 5 } // Query options, see  "bit.ly/mongoose-query-options"
    });