【问题标题】:Trouble inserting array of documents into a database in mongodb via node js script无法通过节点 js 脚本将文档数组插入 mongodb 中的数据库
【发布时间】:2016-06-24 13:02:45
【问题描述】:

我是 node js 和 mongodb 的新手。只是测试一些想法,所以我试图创建一个网络爬虫,将数据添加到 mongodb 的数据库中。我有一个连接到 mongodb 并通过节点 js 脚本将数据动态添加到数据库的脚本。我在控制台中运行这个脚本,如下所示:'node scrapeData.js' 脚本运行没有任何错误,但是当我启动 mongo shell 并运行 db.posts.find() 时,我得到 0 条记录。我知道我的脚本在控制台中记录数据数组时成功地抓取了数据。不知道我哪里错了。这是我的脚本:

var MongoClient = require('mongodb').MongoClient;


//requiring the module so we can access them later on
var request = require("request");
var cheerio = require("cheerio");

MongoClient.connect('mongodb://127.0.0.1:27017/mydb', function (err, db) {
    if (err) {
        throw err;
    } 
    else {
        console.log("successfully connected to the database");

        //define url to download 
        var url = "http://www.nyxcosmetics.ca/en_CA/highlight-contour";

        var prodList = [];
        var priceList = [];
        var products = [];

        request(url, function(error, response, body) {
            if(!error) {


                //load page into cheerio
                var $ = cheerio.load(body);

                $(".product_tile_wrapper").each(function(i, elem) {
                    prodList[i] = $(this).find($(".product_name")).attr("title");
                    priceList[i] = $(this).find($(".product_price")).attr("data-pricevalue");
                });
                prodList.join(', ');

                for(var i = 0; i < prodList.length; i++) {
                    var prod = {
                        name: prodList[i], 
                        price: priceList[i]
                    };
                    products.push(prod);
                }

                console.log(products); //print the array of scraped data

                //insert the prods into the database
                //in the 'posts' collection
                var collection = db.collection('posts');
                collection.insert(products);
                console.log("products inserted into posts collection");

                //Locate all the entries using find
                collection.find().toArray(function(err, results) {
                    console.log(results);
                });

            } else {
                console.log("We've encountered an error!")
            }
        });
    }

    db.close();
});

【问题讨论】:

    标签: javascript node.js mongodb


    【解决方案1】:

    只是一些提示:

    • 您能检查一下您使用的是哪个 mongodb NodeJS 驱动程序版本吗? 1.x2.x 非常不同
    • 在 2.x 驱动程序版本中,db.collection.insert() 实际上已被弃用,取而代之的是更详细的 .insertOne().insertMany()
    • 如果您提供写入回调,您可以调试插入发生的情况,例如

    collection.insert(products, function(error,result) { console.log(error); console.log(result); })

    【讨论】:

    • 感谢您的回复!原来版本不是问题。我用上面的回调代码进行了调试,我得到了一个错误,比如“mongoError:拓扑被破坏”。这与 db.close() 语句有关。显然,我不应该在节点 js 脚本中包含它。我真的习惯了 sql,所以关闭与 db 的连接对我来说似乎很正常,但这在 mongodb 中不是很好的做法。这篇文章对我也有帮助:stackoverflow.com/questions/30425739/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-02
    • 2015-12-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-01
    相关资源
    最近更新 更多