Node.js Mongoose findById检查属性是否存在
我有一个猫鼬模型,比如Node.js Mongoose findById检查属性是否存在,node.js,mongoose,Node.js,Mongoose,我有一个猫鼬模型,比如 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, encodin
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);
}
});
我得到一个错误,说明无法读取属性,问题是记录中没有存储图像属性。我怎么能忽略这一点,不管是否存储了图像
Thanx提前支付。:-) 如果
doc
是未定义的
,您可以检查回调。如果是,则返回其他消息/状态;如果不是,则返回图像
例如:
Model.findById(..., function(err, doc) {
if (err) {...}
else if (doc.image) {<return the image here>}
else {<return a no image found message>}
}
Model.findById(…,函数(err,doc){
如果(错误){…}
else如果(doc.image){}
else{}
}
为了更安全,您可能应该首先检查
doc
是否已定义,因为可以返回空数组/对象,这将导致(doc.image)
检查失败。如果doc
未定义,则可以在回调中检查。如果未定义,则返回其他消息/状态;如果未定义,则返回图像
例如:
Model.findById(..., function(err, doc) {
if (err) {...}
else if (doc.image) {<return the image here>}
else {<return a no image found message>}
}
Model.findById(…,函数(err,doc){
如果(错误){…}
else如果(doc.image){}
else{}
}
为了更安全,您可能应该首先检查doc
是否已定义,因为可能会返回空数组/对象,这将导致(doc.image)
检查失败。请尝试
Model.findById({image:{ $exists: true}}...
试一试
谢谢,我刚刚意识到了这一点。我必须检查文档是否存在吗?我的第一个err check语句不应该包括这一点吗?不,错误只是一个错误,比如无法连接到数据库或其他故障。如果一切都成功,但它没有找到任何东西,它只会返回一个空文档。另一个问题。状态如何如果图像属性丢失,我应该使用代码吗?我正在客户端使用fetch,我知道我需要在更多的地方使用相同的状态代码。我想这取决于可能导致这种情况发生的原因,但我可以想象你会想要400个错误中的一个:谢谢,我刚刚意识到了这一点。我必须检查文档是否存在吗?这不应该是cov吗在我的第一个err check语句中出现错误?不,错误只是一个错误,因为它无法连接到db或其他故障。如果一切都成功,但它没有找到任何东西,它只会返回一个空文档。另一个问题。如果映像属性丢失,我应该使用什么状态代码?我正在客户端使用fetch和understand我需要在更多的地方使用相同的状态代码。我想这取决于是什么导致了这种情况发生,但我想你会想要400个错误中的一个: