簡體   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