【发布时间】:2018-09-20 12:38:14
【问题描述】:
我想保存多个文档,这些文档是在以井号“#”表示的帖子上找到的标签。我在数组中有标签。例如:
var tags = ['banana', 'apple', 'orange', 'pie']
我遍历它们并将它们转换为文档对象(以将它们插入数据库)。问题是我想将一个 new 文档插入到集合中,前提是它之前从未插入过。如果它在我想将插入文档的userCounter 属性增加一之前插入。
var tags = ['banana', 'apple', 'pie', 'orange'];
var docs = tags.map(function(tagTitle) {
return {
title: tagTitle,
// useCounter: ??????????
};
});
var Hashtag = require('./models/Hashtag');
/**
* it creates multiple documents even if a document already exists in the collection,
* I want to increment useCounter property of each document if they exist in the collection;
* not creating new ones.
* for example if a document with title ptoperty of 'banana' is inserted before, now increment
* document useCounter value by one. and if apple never inserted to collection, create a new document
* with title of 'apple' and set '1' as its initial useCounter value
*/
Hashtag.create(docs)
.then(function(createdDocs) {
})
.then(null, function(err) {
//handle errors
});
【问题讨论】:
标签: javascript mongodb mongoose