2016-08-24 84 views
0

我有一個貓鼬模型,如;貓鼬findById檢查屬性是否存在

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提前。 :-)

回答

1

如果docundefined,您可以檢查回調。如果是,則返回其他消息/狀態,如果不是,則返回圖像。

例如:

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)檢查失敗。

+0

謝謝你,我才意識到這一點。我必須檢查文件是否存在?這不應該在我的第一個錯誤檢查聲明中涵蓋? – HenrikG

+0

不,這只是一個錯誤,因爲它無法連接到數據庫或其他故障。如果一切都成功了,但它沒有找到任何東西,它只會帶回一個空文檔 –

+0

另一個問題。如果圖片屬性丟失,我應該使用什麼狀態碼?我在客戶端使用fetch,並理解我需要在更多地方使用相同的狀態碼。 – HenrikG

0

嘗試

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