Node.js 插入多个记录和/或更新特定字段,并仅返回插入的新记录(MongoDB)
嗨,我有一个收藏如下Node.js 插入多个记录和/或更新特定字段,并仅返回插入的新记录(MongoDB),node.js,mongodb,node-mongodb-native,Node.js,Mongodb,Node Mongodb Native,嗨,我有一个收藏如下 var articles = [ { "title": "Article title1", "content": "Article ... content......... 1. ", "url": "http://matt.wordpress.com/article/X", "last_fetche
var articles = [
{
"title": "Article title1",
"content": "Article ... content......... 1. ",
"url": "http://matt.wordpress.com/article/X",
"last_fetched_time": new Date();
},
{
"title": "Article title2",
"content": "Article ... content......... 2. ",
"url": "http://matt.blogger.com/article/Y",
"last_fetched_time": new Date();
}
];
db.collection('articles').insert(articles, {safe:true}, function(err, result) {}); //articles collection created
我希望定期从多个端点并行获取博客提要,并将新文章添加到集合中,并更新集合中现有文章的上次获取日期时间字段。如果我没有要求太多,我还希望upsert的回调只返回插入的新文章
//fetch articles periodically
fetchArticles = function(req, res) {
async.parallel([
//fetch word press endpoint
//get "title", "content", "url"
//set last_fetched_time with new Date();
//fetch blogger endpoint
//get "title", "content", "url"
//set last_fetched_time with new Date();
],
function(err, results) {
//merge results[0] and results[1] in a batch =[]
//if the article url is not already in the collection, insert article into the articles collection
//if the article url is found in the collection, update article because last_fetched_time changed
//finally return only new inserted articles, not updated ones
db.collection('articles').update(batch, {safe:true, upsert : true}, function(err, result) {
//result = only new articles inserted
});
});
}
url字段应该是唯一的,我做到了
db.articles.ensureIndex({"url":1}, {unique: true, sparse:true, dropDups: true});
问题是这段代码没有插入新的文章即使我清楚地看到您在尝试做什么,您的函数似乎也混在一起了 您要传递的
批
包含要插入/更新的文档数组。问题是此功能仅对方法可用
由于您使用的是该方法,因此传递文档数组以进行批处理的选项不可用。如您所做的那样,设置了upsert的更新旨在使用选择器的主要参数和单个“文档”发布。其思想是当选择器
与现有文档匹配时,该文档将使用文档
中的详细信息进行更新。如果未找到匹配项,则插入新文档
此外,由于您尚未使用,因此可以应用multi选项。它的作用是当选择器
匹配多个文档时,更改将应用于所有匹配的文档。未指定行为被视为错误,仅更新找到的第一个匹配文档
看起来,尽管您希望将其与批处理功能一起使用,但它目前并不存在。有一个JIRA,你可以遵循/支持它
请参阅文档中函数的链接,其中解释了所有可用参数和选项。有关选项的详细说明,请参见shell文档:
谢谢Neil,我刚刚试着循环批处理,并对每篇文章进行更新,但我还需要知道每篇文章是否是第一次更新或插入的。但是,对于(var i=batch.length-1;i>=0;i--){articlesCollection.update({'last_-fetched_-time':batch[i]。last_-fetched_-time},batch[i],{safe:true,upsert:true},函数(err,result){if(err){console.log(err);return;}console.log(result);}代码>有一个“w”选项,但是,我不知道如何使用它,而且似乎“safe:true”选项对更新无效,是吗?这是写问题。在文档中查找该术语。答案中的所有链接为您的所有剩余问题提供了充足的文档。更新和插入的行计数不是可访问的。因此,如果记录是insert或update info,则写入问题似乎不会返回。是否有方法使用Mangose之类的驱动程序获取此功能?