HenrikGr
HenrikGr

Reputation: 666

Mongoose findById check if property exist

I have a Mongoose model such as;

var Schema = new Schema({
  title: { type: String, required: true },
  subtitle: { type: String, required: true },
  text: { type: String, required: true },
  image: { data: Buffer, contentType: String, name: String, size: Number, encoding: String }

});

I perform a

let projection = "image";
Model.findById(req.params.id,projection, function (err, doc) {
  console.log(err);
  if (err) {
    res.status(422).json(err);
  }
  else {
    res.contentType(doc.image.contentType);
    res.send(doc.image.data);
  }
});

I get the error stating that can not read property and the problem is there is no image property stored in the record. How can I ignore this, it should not matter if an image is stored or not.

Thanx in advance. :-)

Upvotes: 3

Views: 6771

Answers (2)

Sergiy Voytovych
Sergiy Voytovych

Reputation: 497

Try

 Model.findById({image:{ $exists: true}}...

Upvotes: 6

Dave V
Dave V

Reputation: 1976

You could check in the callback if doc is undefined. If it is, return some other message/status, if it is not, return the image.

For Example:

Model.findById(..., function(err, doc) {
    if (err) {...}
    else if (doc.image) {<return the image here>}
    else {<return a no image found message>}
}

For even more safety, you should probably check that doc is defined first, since it's possible to return an empty array/object, which would cause the (doc.image) check to fail.

Upvotes: 1

Related Questions