I have two models in user.js
and userProfile.js
of mongoose, where I want to get documents using a join query but I have not take ref in user schema so I have code as below:
user.js
var userSchema = new Schema({
nick_name:{type:String},
email: {type: String},
password: {type: String},
is_active:{type:String,enum:['1','0'],default:"1"},
},{ collection: 'user'});
userProfile.js
var userProfileSchema = new Schema({
user_id:{type:Schema.Types.ObjectId, ref:'User'},
first_name:{type:String},
last_name:{type:String},
address:{type:String},
country:{type:String},
state:{type:String},
city:{type:String},
gender:{type:String,enum:['m','f','o'],default:"m"},
is_active:{type:String,enum:['1','0'],default:"1"},
},{ collection: 'userProfile'});
server.js
app.get('/api/userLists', function(req, res) {
User.find({},"nick_name email",function(err, user) {
if(err) {
res.json(err);
} else {
var userIds = user.map(function(obj){
return obj._id;
});
UserProfile.find({user_id:{$in:userIds}},function(err,userProfiles){
if(err){
res.json(userProfiles);
console.log(userProfiles);
}else{
---------------------------------
-What to do here, I have no idea.-
---------------------------------
res.json(user);
}
});
}
});
});
expected output as follows
{
"nick_name" : "laxman",
"email" : "laxman@mailinator.com",
"first_name" : "my first name",
"last_name" : "my last name",
"address" : "my address",
"country" : "my country",
"state" : "my state",
"city" : "my city",
"gender" : "m",
}
**OR**
{
"nick_name" : "laxman",
"email" : "laxman@mailinator.com",
"profile" :{
"first_name" : "my first name",
"last_name" : "my last name",
"address" : "my address",
"country" : "my country",
"state" : "my state",
"city" : "my city",
"gender" : "m",
}
}
dependencies
"express" => "version": "4.7.4",
"mongoose" => "version": "4.4.5",
"mongodb" => "version": "2.4.9",
"OS" => "ubuntu 14.04 lts 32bit",