通过node-js脚本将文档数组插入mongodb中的数据库时出现问题
Trouble inserting array of documents into a database in mongodb via node js script
我是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);
})
相关文章:
- 使用 jQuery UI 折叠面板显示 couchDB 数据库搜索结果时出现问题
- Ajax发布到PHP脚本,每5秒查询一次MySQL数据库的性能/问题
- 将捕获的图像插入数据库问题(Cordova/SQlite/JavaScript)
- 使用数据库中的图像填充dropzone.js删除图像的问题
- PhoneGap 中的数据库条目出现问题
- 在调用 ajax 和查询数据库时遇到问题
- 通过node-js脚本将文档数组插入mongodb中的数据库时出现问题
- 使用 sequelize ORM 连接到节点上的 Amazon RDS Postgres 数据库.js出现问题
- jquery下拉列表和发布到SQL数据库问题
- 根据类别从数据库中调用不同类型的问题
- 电影数据库“访问控制允许来源”问题
- 使用html、php、js从数据库中删除行时出现问题
- 可排序数据和更新数据库问题
- 在javascript中插入SQLite数据库时出现问题
- 在不处理数据库的情况下解决相同的问题
- couchDB数据库根问题
- 角度拖放保存在数据库中的位置和屏幕大小调整问题
- 与数据库的连接以及与输入处理有关的离子问题
- 通过javascript函数从数据库获取php数据时出现问题
- Tinymce编辑器检索数据从数据库问题[striping反斜杠]