Node.js,Express和Mongoose,未定义的数据

只是一个noob问题:

我试图使用属性“封面”来删除与该集合相关的文件,但问题是,它显示为“未定义”。 有没有人有这样的问题? 谢谢 !!!

这是我的日志:

完整结果 – {__v:0,_id:5329a730e4b6306a08297318,

公司:'asd',

封面 :'44f4a87035bd22c1995dcf0ab8af05b0',

描述:'asd',

kind:'asd',

名称:'asd'}

RESULT COVER – 未定义

这是我的代码:

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函数将调用它的callback与文档的数组,而不是一个单一的文档,所以你应该改变你的代码与以下内容:

 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 (这个callback与第一个结果,更快):

 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) ,在这里你logging一个string,你有一个string和一个数组之间的string连接操作。 当你试图用非string连接一个string时,javascript试图强制它变成一个string,所以在不是undefined / null的情况下,它会调用值的.toString方法。 数组的.toString方法实际上会return this.join(',')join方法也是一个string连接。 该数组包含文档,所以JavaScript尝试将文档转换为string(实际上是对象),并调用document.toString() 。 这是通过mongoose实现返回对象的属性,这应该是类似于util.inpsect(document); 。 这个事件的另一个例子是得到的result is 1'result is ' + [1]

为了避免这个问题,我build议,避免使用string连接对象。 而不是console.log('result is ' + object)尝试做console.log(object)console('result is', object)

更新:

我刚刚意识到你也是在调用findOneAndRemove的同时调用find,这是一个竞态条件。 可能发生.find调用不会find任何内容,因为.findOneAndRemove可能已经完成。 这可能会带来更多的问题。