[英]Mongoose find search if statement error using expressjs
這是一個URL縮短項目
app.get('/:url', (req,res) => {
Url.find({userUrl:req.params.url},(err,doc)=>{ //finds if there is a link in the database
if(err){
console.error(err)
}else if(doc[0].userUrl==req.params.url) { // there is an error in this line if a new link is passed in the params.url, or else if the link existed then there is no issue
console.log('hi')
}else { // if no link is not reaching?
const url = new Url({
userUrl:req.params.url
})
url.save();
}
})
})
如果我在數據庫示例google.com中有一個鏈接,它確實為我提供了hi的輸出,但是當我放置其他鏈接時,它在第一個else if語句中為我提供了“ property userUrl undefined”錯誤。
我的模式就是這樣let urlsSchema = new Schema({ userUrl:String, shortUrl: { type: String, 'default': shortid.generate } })
const Url = mongoose.model('urls',urlsSchema);`
我認為我需要以某種方式編寫它,如果您在數據庫中找不到它,則創建一個新的url文檔。
主要問題是,僅當請求已損壞或數據庫連接不起作用時, find
才會引發錯誤。 如果未找到任何數據,它將不會返回錯誤,而是返回一個空的doc
數組。 如果然后訪問doc[0]
,它將返回undefined,並且undefined沒有userUrl
。 一個可能的解決方案是檢查doc數組是否有第一個文檔:
Url.find({ userUrl: req.params.url }, (err, doc) => {
if(err){
return console.error(err);
if(doc[0]){
//Exists already
console.log(doc[0]);
} else {
//Doesnt exist yet, so create a new one:
const url = new Url({
userUrl: req.params.url
})
url.save();
}
});
請注意,您應該使用findOne
來檢查是否存在。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.