繁体   English   中英

node.js异步数组将数据保存到mongodb

[英]node.js async array save data to mongodb

我有一个弦

var my_str = "Jenny [id:51], david, Pia [id:57], Aston [id:20], Raj, ";

我将其发送到函数convert_to_array(my_str)并希望得到类似这样的东西

[all: [51, 72, 57, 20, 73], new: [72, 73]]

在这里,72和73是新插入到mongodb数据库的文档。

这就是我在做什么:

function convert_to_array(text) {
if(text && text !== '') {

    var text_arr = text.split(', ');
    text_arr.pop();

    var arr = new Array();
    var new_profiles = new Array();
    var all_profiles =  new Array();

    for(var i = 0; i < text_arr.length; i++) {
        var pair = text_arr[i].split('[id:');

        // Its already existing, just add it to the array
        if(pair[1]) {
            all_profiles.push(pair[1].split(']')[0]);

        // Else create a new profile and pass the _id
        } else {

            // Save to db first
            var profileObj = new Profile({name: pair[0], automated: true});
            profileObj.save(function(err, data) {

                if(err) throw err;

                all_profiles.push(String(data._id));
                new_profiles.push(String(data._id));
            });
        }
    }
    arr = {all: all_profiles, new: new_profiles};
    return arr;
}
}

有了这段代码,我只能得到这个(或者类似的东西,我不记得确切的输出了)

    [all: [51, 57, 20], new: []]

该项目保存在数据库中,我可以看到。 但是由于节点本质上是非阻塞的,因此for循环完成并返回,然后将数据保存在数据库&中,并将id推送给aray。 我尝试使用异步,但仍然不知道如何解决此问题。

我添加了一些console.logs来查看其执行方式,如下所示:

yes existing: 51
oh! doesnt exist. creating: david
yes existing: 57
yes existing: 20
oh! doesnt exist. creating: Raj
GET /page/delete_later 200 4ms
Ok created now: 72
Ok created now: 73

我对如何编写对节点友好的代码感到困惑!

您需要更改您的convert_to_array函数,以便在完成结果后调用回调,而不是将结果返回一个返回值。

function convert_to_array(text, callback) {
   // do some stuff, call this when done:
   //    callback(null, arr);
   // or this on error:
   //    callback(err);
}

现在准备好结果了吗? 这是处理完所有text_arr项的时间(即,对profileObj.save所有调用已完成)。 可能最简单的方式来表达此代码是使用异步模块( npm install async ):

var async = require('async');
// ...

function convert_to_array(text, callback) {
  if(text && text !== '') {

    var text_arr = text.split(', ');
    text_arr.pop();

    var arr = new Array();
    var new_profiles = new Array();
    var all_profiles =  new Array();

    async.eachSeries(text_arr, function(it, done) {
      var pair = text_arr[i].split('[id:');

      // Its already existing, just add it to the array
      if(pair[1]) {
        all_profiles.push(pair[1].split(']')[0]);
        next(); // !important! tell async we are done
      // Else create a new profile and pass the _id
      } else {
        // Save to db first
        var profileObj = new Profile({name: pair[0], automated: true});
        profileObj.save(function(err, data) {
            if(err) {
              // throw err; // use callback instead of throw for error handling
              next(err);
              return;
            }
            all_profiles.push(String(data._id));
            new_profiles.push(String(data._id));
            next(); // !important! tell async we are done
        });
    }, function(err) { 
      arr = {all: all_profiles, new: new_profiles};
      callback(err, arr);
    }

  } else {

    callback(null, undefined); // alter depending on your requirements
  }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM