简体   繁体   English

Node.js + Mongoose ......控制流量问题?

[英]Node.js + Mongoose… Control flow issue?

Just started to play around with node.js, have some past experience with JavaScript but very little in server-side. 刚刚开始使用node.js,有一些过去的JavaScript经验,但在服务器端很少。

I have the below code and the functionality that I'm looking for is too add a product to the collection using Mongoose, however, if a duplicate is found using 'name', then push the product as an embedded document to the duplicate, with only select information, such as product_ids, package info, etc. I'm assuming that the problem has to do with findOne not finding any duplicates on the first run. 我有以下代码,我正在寻找的功能是使用Mongoose将产品添加到集合中,但是,如果使用'name'找到副本,则将产品作为嵌入文档推送到副本,只选择信息,例如product_ids,包信息等。我假设问题与findOne在第一次运行时没有找到任何重复项有关。 If I run it a second time, it does detect the duplicates, but by then it's too late. 如果我第二次运行它,它确实检测到重复,但到那时为时已晚。 I'm not sure how to get findOne to run only after the previous 'save' occurred. 我不确定如何在前一次“保存”发生后才让findOne运行。

function insertProduct(data) {
    var product;
    Product.findOne({
        name: data.name
    }, function(err, doc) {
        if (err) throw err;
        if (!doc) {
            product = new Product({
                name: data.name
                //other product data
            });
            product.packages.push({
                //package data
            });
        }
        else if (doc) {
            doc.packages.push({
                //package data
            });
            product = doc;
        }
        product.save(function(err) {
            if (err) throw err;
            console.log('Added: ' + product.name);
        });
    });
}

request(url, function(error, response, body) {
   if (!error && response.statusCode === 200) {
      jsonResult = JSON.parse(body);
      jsonResult.result.forEach(insertProduct);
   }
});

I realize this has to be an issue with control flow, that I'm still trying to get a hold of. 我意识到这必须是控制流程的一个问题,我仍然试图抓住它。 Your help is appreciated! 非常感谢您的帮助!

Welcome to the world of non-blocking IO, and JavaScript closures :) 欢迎来到非阻塞IO和JavaScript闭包的世界 :)

A simpler way around it is by separating the product creation and push the packages after the product is successfully created. 更简单的方法是分离产品创建并在成功创建产品后推送包。

addProduct = function(name, next) {
  Product.findOne({name: name}, function(err, doc) {
    if(doc) {
      next(null, doc);
    }
    else {
      // create new product...
      var d = new Product({name: name});
      next(null, d);
    }
  });
});

// ... snipped

jsonResult.result.forEach(function(item) {
  addProduct(item.name, function(err, doc) {
    if(err == null) {
      doc.packages.push({
        // stuffs
      });
      doc.save();
    }
  });
});

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

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