0

I have schemas of user, and pet. User can have a few pets. I need the user name that the pet belongs to.

var petSchema = new Schema({
    name: { type: String, required: true },
    user: { type: Schema.Types.ObjectId, ref: 'User', required: false },
});
var userSchema = new Schema({
    name     : { type: String, default: 'New User', required: true },
 });

I try:

Pet.find({name:'koko'},"user user.name ", function(err,user){
    res.send(user);
});

But I don't get the user name.

jivangilad
  • 469
  • 10
  • 21
  • 2
    You are attempting a join? Well, there are no joins in mongodb. You either embed the user info in the pet or do the join itself on the client side. – joao Jan 28 '15 at 09:15

1 Answers1

2

You should use populate method

i.e.

Pet
.findOne({ .... })
.populate('user')
.exec(function (err, pet) {
  if (err) return handleError(err);
  res.send(pet.user)
})
marcinn
  • 1,786
  • 11
  • 13