[英]mongoose express node.js javascript function return undefined
[英]Node.js, Express and Mongoose, undefined data
只是一個菜鳥問題:
我正在嘗試使用屬性“ cover”刪除與該集合相關的文件,但是問題是它顯示為“ undefined”。 有人遇到過這樣的問題嗎? 謝謝 !!!
這是我的日志:
完整結果-{__v:0,_id:5329a730e4b6306a08297318,
公司:“ asd”,
封面 :'44f4a87035bd22c1995dcf0ab8af05b0',
說明:“ asd”,
種類:“ asd”,
名稱:“ asd”}
結果覆蓋- 未定義
這是我的代碼:
exports.delete = function(req,res){
if(!req.session.authorized){
res.json(403,{message:'YOU MUST BE LOGGED IN'});
return;
}
Product.find({_id:req.params.id}, function(err,result){
if (err){
res.json(401, {message: err});
}else{
console.log("FULL RESULT - " + result);
console.log("RESULT COVER - " + result.cover);
var prodCoverName = result.cover;
if (prodCoverName){
fs.exists('public/productAssets/'+ prodCoverName, function (exists) {
console.log('EXIST - public/productAssets/'+ prodCoverName);
fs.unlink('public/productAssets/'+ prodCoverName, function (err) {
if (err) throw err;
console.log('DELETED AT public/productAssets/'+ prodCoverName);
});
});
}
}
});
Product.findOneAndRemove({_id:req.params.id}, function(err,result){
if (err) res.json(401, {message: err});
else res.json(200, {message: result});
});
};
我不是貓鼬方面的專家,但我的猜測是Product.find
函數將使用文檔數組而不是單個文檔來調用它的回調,因此您應該使用以下代碼來更改代碼:
Product.find({_id:req.params.id}, function(err, results){
var result = results[0]; // either one result or nothing, because id is unique and we want the first result only.
或改為使用findOne (此方法以更快的速度返回第一個結果):
Product.findOne({_id:req.params.id}, function(err, result){
或使用findById (更短,更快):
Product.findById(req.params.id, function(err, result){
現在您可能會問,為什么在我的情況下,“全結果”是一個對象。 這是在javascript中發生的事情:
您具有console.log("FULL RESULT - " + result)
,這里您正在記錄一個字符串,並且在字符串和數組之間進行了字符串串聯操作。 當您嘗試將字符串與非字符串連接時,javascript會嘗試將其強制轉換為字符串,因此在並非未定義/為空的情況下,它將調用該值的.toString
方法。 數組的.toString
方法實際上確實return this.join(',')
。 join
方法也是字符串連接。 該數組包含文檔,因此javascript嘗試將文檔轉換為字符串(實際上是對象),然后調用document.toString()
。 它由貓鼬實現以返回對象屬性,該屬性應類似於util.inpsect(document);
。 此事件的另一個示例是得到的result is 1
'result is ' + [1]
。
為了避免這個問題,我建議,只需避免用字符串連接對象。 代替console.log('result is ' + object)
嘗試做console.log(object)
或console('result is', object)
。
更新:
我只是意識到您在調用find的同時也正在調用findOneAndRemove,這是一種競爭條件。 .find
調用可能找不到任何東西,因為.findOneAndRemove
可能已經完成。 這可能會帶來更多問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.