繁体   English   中英

无法通过节点js脚本将文档数组插入mongodb中的数据库

[英]Trouble inserting array of documents into a database in mongodb via node js script

我是Node js和mongodb的新手。 只是测试一些想法,所以我试图创建一个Web刮板,将数据添加到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();
});

只是一些提示:

  • 您可以检查使用的是哪个mongodb NodeJS驱动程序版本吗? 1.x2.x有很大的不同
  • 在2.x驱动程序版本中,实际上不建议使用db.collection.insert() ,而是使用更详细的.insertOne().insertMany()
  • 如果提供写回调,则可以调试插入操作发生的情况,例如

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

暂无
暂无

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

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