Ayrton Dumas Ayrton Dumas - 2 months ago 11
Node.js Question

Node + Mongoose, wait for result before saving

I am actually trying to save a new record in my mongodb databse.

company.save(function(err, company){
if (err)
//fail;

//success
})


But, before this action, i'd like to add tags to my company

My company schema

var companySchema = new mongoose.Schema({
name: String,
accro: String,
npa: String,
city: String,
country: String,
isverified : Boolean,
tags: [{
type: mongoose.Schema.Types.ObjectId,
ref: 'Tag' // réf. tagSchema
}
]
})


as you can see, tags is a ref so i'm checking if the tag already exists or not:

for (var i = 0; i < req.body.tags.length; i++) {
var currentTag = req.body.tags[i];

Tag.findOne({'label': currentTag }, function(err,t){
var tag_id = "";

if(err) res.send(err);

// if exist
if (t) {
console.log("#" + i + " currentTag existe");
t.use++;
t.save();
tag_id = t._id;

} else {

console.log("#" + i + " currentTag not existe");
var tag = new Tag();
tag.label = currentTag;
tag.save();
tag_id = tag._id;
}

company.tags.push(tag_id);

});
}


but as the mongoose findOne function has a callback, the loop just keeps "looping" and when the
company.save()
is fired, no tags has been added to the company..

Need some help to get it asynchronous :) Thanks

Answer

You need not to find tags one by one. use $in operator like below:

Tag.find({'label': {$in: req.body.tags}},function(err,oldTags){


            if(err) res.send(err);
var tag_id = '';
            for(var i = 0; i < req.body.tags.length; i++){
              for(var j = 0; j < oldTags.length; j++){

              if(req.body.tags[i] == oldTags[j].label){
               oldTags[j].use++;
               oldTags[j].save();
               tag_id = oldTags[j]._id;
              } else {
              console.log("#" + i + " currentTag not existe");
              var tag = new Tag();
              tag.label = req.body.tags[i];
              tag.save();
              tag_id = tag._id;
              }
              company.tags.push(tag_id);

            }
            }
// HERE SAVE YOUR COMPANY OBJECT
        });