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

Node.js, Express and Mongoose, undefined data

本文关键字:未定义 数据 Mongoose Express js Node      更新时间:2023-09-26

这是一个新手问题:

我试图使用属性"cover"来删除与该集合相关的文件,但问题是它显示为"未定义"。有人遇到过这样的问题吗?谢谢! !

这是我的日志

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

公司:"自闭症",

覆盖:"44 f4a87035bd22c1995dcf0ab8af05b0",

描述:"自闭症",

:"自闭症",

name: 'asd'}

RESULT COVER - undefined

下面是我的代码:
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){
现在你可能会问,为什么在我的例子中,FULL RESULT是一个对象。下面是javascript中的代码:

你有console.log("FULL RESULT - " + result),在这里你记录一个字符串,你有字符串连接操作,在字符串和数组之间。当你试图连接一个字符串与非字符串,javascript试图强制它成一个字符串,所以在情况下,它不是未定义/null它会调用.toString值的方法。数组的.toString方法实际上执行return 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可能已经完成了。这可能会带来更多的问题。