Lee Morgan
Lee Morgan

Reputation: 696

What is the NodeJS mongoDB client equivalent to Mongoose populate?

I am trying to switch over from use Mongoose to using the MongoDB driver for JavaScript. Inside some of my documents I have relationships with others. I was wondering about how to "populate" these. With Mongoose I can do something like:

Collections.find().populate("field")

I am wondering how would I do the equivalent with the MongoDB driver. Is there some function for doing that? Or, ideally, maybe some way to do it within the aggregation pipeline? Thanks for any help.

Upvotes: 1

Views: 1337

Answers (1)

Cesar Adan
Cesar Adan

Reputation: 19

Yes, it is. You can do it.

You can create a function:

exports.joinRetailCollection = (collectionName, collectionJoinName, foreignFieldName, asFieldName) =>  state.db.collection(collectionName).aggregate([
  { 
    $lookup: 
    {
      from: collectionName,
      localField:  collectionJoinName,
      foreignField: foreignFieldName,
      as: asFieldName
    }
}
]);

from: 'user',
localField: 'products',
foreignField: 'sku',
as: 'inventory'

and import it in

enter code here

const {db} = require('../route');

and create a variable

const userLink = db.joinRetailCollection('user', .....) //the arguments of the function.

Add this to your mongo-connector.js file

const MongoClient = require('mongodb').MongoClient

const state = {
  db: null,
}

exports.connect = async (url, done) => {
  if (state.db) return done()
  MongoClient.connect(url, { 
    connectTimeoutMS: 200,
    retryWrites: true,
    useNewUrlParser: true, 
    useUnifiedTopology: true }, (err, client) => {
    if (err) return done(err)
    state.db = client.db('wp_test')
    done()
  })
}`

exports.getCollection = (collectionName) => state.db.collection(collectionName);

and then the fnctions you also add one for collection only in the same file

Hope this will be useful for you.

Kind regards

Upvotes: 1

Related Questions