문제

This is the situation: I have two schemes and I receive an Object like this:

{ net: '192.168.1.1/28',
  ips: [ { ip: '192.168.1.1', ports: [Object] } ] }

schemes:

var portSchema = new mongoose.Schema({ 
    port: Number,
    state: String,
    protocol: String,
    service: String
});
exports.targetSchema = new mongoose.Schema({  
         ip: String,
         mac : String,
         ports: [portSchema]
    });
exports.NetSchema = new mongoose.Schema({ 
   net: String,
   mask: String,
   ips: [{type : mongoose.Schema.ObjectId, ref : 'target'} ]
});

As you can guest I save "net" key into NetSchema model and all "ips" array content are saved to targetSchema. The trouble is that I don't know how to update NetSchema when I add all targetSchemas. What I want to say is that "save" is asynchronous and I can't update NetSchema until targetSchema is completly saved. This is my try:

async.series([
    function(callback){
         netw = new Net({net: dev.net});
     for(var k = 0; k< dev.ips.length; k++){
         var targets = new Targets(dev.ips[k]);
         targets.save(function(err, doc) {
                 ips.push(doc._id); 
             callback();
         });
      }
    },
    function(callback){
       netw.ips=ips; 
       netw.save();
}]);

Just save the fist one target because save function is asynchronous and the next fucntion is executed before I want.

도움이 되었습니까?

해결책

Finally I've found mapLimit from async library to do it. :)

async.mapLimit(dev.ips, 1, function(info, next){ 
            var targets = new Targets(info);
            targets.save(function(err, doc) {
                ips.push(doc._id);
                next();
            });
        }, function(err, results){  
            var netw = new Net({"net": dev.net, "ips":ips});
            netw.save(function(){
                console.log("guardado")
            });

        });

Do you know a better option?

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top