只是一个菜鸟问题:
我正在尝试使用属性“cover”来删除与该集合相关的文件,但问题是它显示为“未定义”。有人遇到过这样的问题吗??谢谢!!!
这是我的日志:
完整结果 - { __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});
});
};
最佳答案
我不是 Mongoose 方面的专家,但我的猜测是 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){
现在您可能会问,为什么在我的例子中,FULL RESULT 是一个对象。这是在 javascript 中发生的事情:
您有 console.log("FULL RESULT - "+ result)
,在这里您正在记录一个字符串,并且您在字符串和数组之间进行字符串连接操作。当您尝试将字符串与非字符串连接时,javascript 会尝试将其强制转换为字符串,因此在它不是 undefined/null 的情况下,它将调用 .toString
值的方法。 .toString
数组的方法实际上确实 返回 this.join(',')
。 join
方法也是一个字符串连接。该数组包含文档,因此 javascript 尝试将文档转换为字符串(它们实际上是对象)并调用 document.toString()
.这是mongoose实现的返回对象属性,应该类似于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
可能已经完成。这可能会引入更多问题。
关于javascript - Node.js、Express 和 Mongoose,未定义数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22509247/