Mongodb查看数组中是否存在所有项目并更新其他插入

时间:2016-03-23 16:09:58

标签: javascript node.js mongodb express mongoose

我有一个mongo标签集合,当用户输入标签数组时,我想执行以下操作:

如果数组中存在标记,请更新计数 如果数组中的标记不存在,则插入计数为0

我目前有:

QuestionTags.update({'tag': {$in: tagArray}}, {$inc : {'count': +1} }, { upsert: true });

QuestionTags是db集合的mongoose模式。

这似乎不起作用。我输入了一个新标签数组,但没有添加它们,并且现有标签没有增加。

有没有办法处理这个问题而无需循环遍历tagArray并为数组中的每个项目进行数据库调用?

更新: 将我的代码更改为此

QuestionTags.update({'tag': {$in: req.body.tags}}, {$inc : {'count': +1} }, { upsert: true, multi: true });
QuestionTags.find({'tag' :{$nin: req.body.tags}}, function(err, newTags) {
    console.log("New Tags :" + newTags);
    var tagArray = [];
    newTags.forEach(function(tag){
        var tagObj = {
            tag: tag,
            count: 1
        }
        tagArray.push(tagObj);
    });
    QuestionTags.collection.insert(tagArray);
});

但是,newTags为空。 QuestionTags集合目前为空,因此它不应为null。

1 个答案:

答案 0 :(得分:1)

我认为您可以在几个查询中执行此操作,而无需循环查询。

1)更新现有标签计数:您的查询有效:

QuestionTags.update({'tag': {$in: tagArray}}, {$inc : {'count': +1} },{multi: true} );

2)找到新标签:

QuestionTags.find({},function(err, tags) {
    var newTagObj = [];

    // tags is originally an array of objects
    // creates an array of strings (just tag name)
    tags = tags.map(function(tag) {
        return tag.tag;
    });

    // returns tags that do not exist
    var newTags = tagArray.filter(function(tag) {
        // The count = 1 can be done here
        if (tags.indexOf(tag) < 0) {
            tag.count = 1;
        }

        return tags.indexOf(tag) < 0;
    });

    // creates tag objects with a count of 1
    // adds to array
    // (this can be done in the previous loop)
    newTags.forEach(function(tag) {
        var tagObj = {
            tag: tag,
            count: 1
        }
        newTagObj.push(tagObj);
    });

这将为您提供数据库中不存在的标记数组。

3)在find回调中使用结果2插入新标签:

QuestionTags.collection.insertMany(newTagObj);