I am trying to make a populate query with mongodb (using mongoose as orm), and it doesn´t work 100%. I mean that I get all the entries from the document where I apply the populate... ALL, the entries that (on the crossed document) match with the match query (and I obtain a nested object), but I get the others too (and the nested object is null).
This is what I have done:
MODELS
var userSchema = Schema({
name: String,
email: String,
idiom: String
});
var ticketsSchema = Shema({
user_id:{ type:Schema.Types.ObjectId, ref:'User', required: true},
date: Date,
points: Number,
kart: String
});
POPULATE
tickets.find()
.populate(
{
path: 'user_id',
match:{name:"user1"}
}
).exec(function (err, result) {
if (err) return handleError(err);
res.send(result);
});
And a possible result could be:
Object[0]
__v: 0
_id: "5655b68ccbe953bc2a78da54"
date: "2015-11-25T13:24:28.561Z"
date: "2015-11-25T13:24:28.561Z"
points: 50
kart: "Senior"
user_id: Object
__v: 0
_company: 0
_id: "5655b656cbe953bc2a78da53"
name: "user1"
email: "user1@mail.com"
idiom: "es"
Object[1]
__v: 0
_id: "5655b732e0685c441fddb99b"
date: "2015-11-25T13:27:14.608Z"
points: 75
kart: "Pro Senior"
user_id: Object
__v: 0
_company: 0
_id: "5655b656cbe953bc2a78da53"
name: "user1"
email: "user1@mail.com"
idiom: "es"
Object[2]
__v: 0
_id: "56564613701da2981aa017d6"
date: "2015-11-25T23:36:51.774Z"
points: 75
kart: "Pro Senior"
user_id: null
Object[3]
__v: 0
_id: "565646ee701da2981aa017d8"
date: "2015-11-25T23:40:30.308Z"
points: 75
kart: "Pro Senior"
user_id: null
This isn´t exactly what I want to do... I would want that the two last doesn´t show up.
EDIT
I think I didn´t explain clear myself clearly... what I want to do is a JOIN query...
I have seen that I need use a mapreduce, I tried to do but I don´t found a place where it is explained for... dummies. All what I could do until now is this:
ticketsDB.find()
.populate(
{
path: 'user_id',
match:req.body
}
).exec(function (err, result) {
if (err) return res.send(err);
reslt=[];
for(var i in result)
if(result[i].user_id)reslt.push(result[i]);
console.log(reslt);
res.send(reslt);
});
Thank you.