Reputation: 1434
Following is the code which i am trying to run :-
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);
})*/
}
})
i have views entry in my model class as well. But i keep getting this error :- [TypeError: Cannot read property '_id' of undefined]
Upvotes: 0
Views: 2810
Reputation: 311835
You can't use a full Mongoose model instance as a findByIdAndUpdate
update parameter, and that's what you're trying to do by passing pools[i]
into that method call.
Instead, after modifying pools[i]
, call its save
method:
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+'');
}
}
Upvotes: 1
Reputation: 5074
findByIdAndUpdate() is async call, putting it inside a regular for loop won't work. it needs to be in async loop, one of the ways it can be done is to use async.each() or 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');
});
Upvotes: 1