Stefan
Stefan

Reputation: 1071

References in MongoDB / Mongoose / nodejs - parallelization

I want to get references in mongoDB using nodejs/mongoose.

In the documentation I read that there are two options: Manual References or DBRefs.

Since they state, its recommended to use Manual References, I decided to set up a schema in the following way:

var schema = new mongoose.Schema({
    name : String,
    reference : mongoose.Schema.ObjectId
});
  1. Question: If I retrieve an array of these objects from my collection, how do I resolve the references in a good practice way?

My Idea was to use Nimble and parallelize the necessary requests. I wanted to do something like

flow.parallel(functions, function() {
    return result;
}); 

where I dynamically fill an array of functions

var functions = []

which I pass then to nimble. (kind of this SO-question: Javascript Array of Functions)

  1. Question: Is this practical? The array of functions-thing seems kind of not really the way to go to me. But I don't see any alternative, since nimble needs to be called with a static number of functions.

Upvotes: 0

Views: 221

Answers (1)

JohnnyHK
JohnnyHK

Reputation: 312035

You can use Mongoose's support for reference population to efficiently follow references.

var schema = new mongoose.Schema({
    name : String,
    reference : { type: mongoose.Schema.ObjectId, ref: 'OtherModel' }
});
var MyModel = mongoose.model('MyModel', schema);
MyModel.find().populate('reference').exec(function(err, docs) {...});

In the above example, the reference field of each docs element gets populated with referenced doc.

Upvotes: 1

Related Questions