Reputation: 494
I have these two simplified schema which I'd like to "join" based on ip address.
var personSchema = Schema({
name: String,
ip: String
});
var logSchema = Schema({
message: String,
ip: String
});
It would work if person._id was the ip address. But it's not an options for me.
Currently I've solved the problem the way that when new log is saved, I search the person and add reference to log. Schema is then like this:
var logSchema = Schema({
message: String,
ip: String,
person: { type: Schema.Types.ObjectId, ref: 'Person' }
});
I've read mongoose Populate documentation, Document#populated and Model.populate(). I'm still not sure if it is possible or not. This example is very simplified, I use mapReduce and grouping on log collection and therefore population would be great for me.
I've also read Database references and it seems to me that the only option is to populate based on _id. But it's pure mongodb and maybe there is another possiblity using mongoose?
Is it possible to populate query not based on _id field?
Upvotes: 3
Views: 3305
Reputation: 2656
MongoDB 3.2 introduces a $lookup aggregate. You can use this with mongoose also. This is an example of how to use it with a conditional find
also:
Log.aggregate(
{ $match: {log_property: 'value'}},
{ $lookup: {from: 'person', localField: 'ip', foreignField: 'ip', as: 'user'} }
).exec( function (err, logs) {
if (err) {
next(err);
}
res.json(logs);
}
);
In the above example, the user
property on each log will be filled in with the person from the matching Person model document
Upvotes: 1
Reputation: 56467
MongoDB does not support joins. So .populate
just makes another query, therefore the best solution for you is to make another query manually.
Upvotes: 1