singhakash
singhakash

Reputation: 7919

Search by ObjectId in mongoose schema nodejs

I am using mongoose with nodejs . I have item schema and user schema given below.

var userSchema = new Schema({
  email: { type: String, required: true, unique: true },
  password: { type: String, required: true },
  items : [{ type: Schema.Types.ObjectId, ref: 'Item' }]
});

var itemSchema = new Schema({
  name: { type: String, required: true },
  _owner : { type: Schema.Types.ObjectId, ref: 'User' }
});

I am trying to find item by user id(_owner in item schema).

I have tried to find directly

var uid = req.decoded._id;
var item = Item.findOne({"_owner": uid});
console.log(item.name);   // undefined

By searching similar I found that id needs to be in ObjectId object so I tried

var uid = new mongoose.Types.ObjectId(req.decoded._id);
var item = Item.findOne({"_owner": uid});
console.log(item.name);   // undefined 

In both the cases item.name is undefined .Note that I have rechecked the value of req.decoded._id(by printing) with the db so it not undefined and present in db.

Is there anything I am doing wrong?

Upvotes: 1

Views: 700

Answers (1)

JohnnyHK
JohnnyHK

Reputation: 311835

Model.findOne is an async call. It doesn't return the doc, it passes it to a callback function that you need to provide as a second parameter.

var uid = req.decoded._id;
var item = Item.findOne({"_owner": uid}, function(err, item) {
    console.log(item.name);
});

Upvotes: 2

Related Questions