通过node-js脚本将文档数组插入mongodb中的数据库时出现问题

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

本文关键字:数据库 问题 mongodb 脚本 node-js 文档 插入 数组 通过      更新时间:2023-09-26

我是node js和mongodb的新手。只是测试了一些想法,所以我试图创建一个web scraper,将数据添加到mongodb中的数据库中。我有一个脚本,它连接到mongodb,并通过node-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.x和2.x非常不同
  • 在2.x驱动程序版本中,db.collection.insert()实际上已被弃用,取而代之的是更详细的.insertOne().insertMany()
  • 如果你提供了一个写回调,你可以调试插入时发生的事情,例如

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