Vote count:
0
I've got a seed file setup to populate my mongodb. I am setting up a counter so I can automatically increment a value when I add a new recipe to my db. Right now I'm using async.series to run the different tasks in the seed file. In what I've included you can see where I set recipe_id equal to this methods return value getNextSequence(counters, "recipeid")
getNextSequence uses the Counter model to query (findOneAndUpdate) the db. I believe the callback for findOneAndUpdate is never called though because the callback for async.series is invoked first. It's a funny problem though because I need to ensure that getNextSequence has returned successfully before moving on. Not sure the best way to go about this.
//seed.js //incomplete
var getNextSequence = require('./utils/getNextSequence').getNextSequence;
recipes = new mongo.Collection(db, "recipes");
counters = new mongo.Collection(db, "counters");
async.series([
function(callback){
//initiate counter
counters.insert(
{
_id: "recipeid",
seq: 0
},function(err, rec){
callback(err, rec);
})
},
function(callback){
//add test recipes
recipes.insert([{
recipe_id: getNextSequence(counters, "recipeid"),
title:'title 1',
body:'body 1',
author: [seedUsers[1]._id],
categories: [ seedCategories[0]._id, seedCategories[1]._id ],
create_at: new Date()
},{
recipe_id: getNextSequence(counters, "recipeid"),
title:'title 2',
body:'body 2',
author: [seedUsers[1]._id],
categories: [ seedCategories[1]._id ],
create_at: new Date()
}], function(err, rec){
callback(err, rec);
})
}
],
// optional callback
function(err, results){
//console.log('\n', results);
db.close();
});
//getNextSequence.js
var Counter = require('../counter').Counter;
exports.getNextSequence = function(counters, name) {
Counter.findOne({ '_id': 'recipeid' }, function (err, counter) {
//if (err) return handleError(err);
//never called
console.log('---counter seq=', counter.seq);
})
Counter.findOneAndUpdate({ _id: name }, { $inc: { seq: 1 } }, { new: true }, function(err, counter){
//never called
console.log('counter.seq', counter.seq);
return counter.seq;
}
)
}
How to waait for findOneAndUpdate to finish before continuing async.series
Aucun commentaire:
Enregistrer un commentaire