【问题标题】:Cannot read property '_id' of undefined using mongoose无法使用猫鼬读取未定义的属性“_id”
【发布时间】:2014-06-10 15:17:54
【问题描述】:

以下是我要运行的代码:-

        poolModel
        .find({})
        .exec(function (err, pools) {
            if(err)
                return next(new customError.Database(err.toString()));

            for(var i=0; i<pools.length; i++)
            {

                pools[i].views = 31;
                console.log(pools[i]._id);
                var pool_id = pools[i]._id;


                poolModel.findByIdAndUpdate(pool_id, pools[i], function(err, pool){
                   if(err)
                    console.log(err);
                   else
                    console.log(pool.views+'');

                });
               /* poolModel.findByIdAndUpdate(ObjectId(pools[i]._id), pools[i], function(err, pool){
                    if(err)
                        return next(new customError.Database(err.toString()));
                    console.log(pool.views);

                })*/
            }
        })

我的模型类中也有视图条目。 但我不断收到此错误:- [TypeError:无法读取未定义的属性“_id”]

【问题讨论】:

    标签: node.js mongoose


    【解决方案1】:

    您不能将完整的 Mongoose 模型实例用作 findByIdAndUpdate 更新参数,而这正是您试图通过将 pools[i] 传递到该方法调用中来实现的。

    改为在修改pools[i]后,调用其save方法:

    for(var i=0; i<pools.length; i++)
    {
        pools[i].views = 31;
        pools[i].save(function(err, pool){
            if(err)
                console.log(err);
            else
                console.log(pool.views+'');
        }
    }
    

    【讨论】:

      【解决方案2】:

      findByIdAndUpdate() 是异步调用,将其放在常规 for 循环中是行不通的。它需要处于异步循环中,其中一种方法是使用 async.each() 或 async.eachSeries():

      var async = require('async');
      
       :
       :
      
      async.each(pools, function(item, callback) {
        var pool_id = item._id;
        item.views = 31;
        console.log(pool_id);
        poolModel.findByIdAndUpdate(pool_id, item, function(err, pool){
          if(err)
            console.log(err);
          else
            console.log(pool.views+'');
          callback(null);
        });
      }, function(err) {
        console.log('all done');
      });
      

      【讨论】:

      • 我仍然收到同样的错误 [TypeError: Cannot read property '_id' of undefined]
      猜你喜欢
      • 1970-01-01
      • 2016-11-12
      • 2021-09-06
      • 2019-12-11
      • 1970-01-01
      • 1970-01-01
      • 2017-06-15
      • 1970-01-01
      • 2022-07-27
      相关资源
      最近更新 更多