我有一个猫鼬模型,例如;
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 }
});
我执行
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);
}
});
我收到错误消息,指出无法读取属性,问题是记录中没有存储图像属性。我如何忽略这一点,是否存储图像都无关紧要。
提前感谢。:-)
您可以检查回调是否doc
为undefined
。如果是,则返回其他消息/状态,如果不是,则返回图像。
例如:
Model.findById(..., function(err, doc) {
if (err) {...}
else if (doc.image) {<return the image here>}
else {<return a no image found message>}
}
为了获得更大的安全性,您可能应该doc
首先检查定义的对象,因为有可能返回一个空的数组/对象,这将导致(doc.image)
检查失败。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句