MongoDB查询添加和删除数组

时间:2017-05-15 22:01:24

标签: javascript node.js mongodb mongoose

我在这个查询中苦苦挣扎了大约三个小时没有结果。我有这个Mongoose Schema:

var User = mongoose.Schema({
  username: { type: String, required: true },
  email: { type: String, required: true },
  password: { type: String, required: true },
  name: { type: String, required: true },
  surname: { type: String, required: true },
  tags: [{
     type: { type: String },
     name: { type: String }
  }, { _id: false }]
};

我需要对tags数组执行一些操作。我需要做的是简单地添加和删除客户端发送的标签。我创建了两个嵌套查询:

    updateTagsById: function(id, obj){
        var add = [];
        var remove = [];
        for (var i = 0; i < obj.add.length; i++) {
            add.push({ type: obj.type, name: obj.add[i] });
        }
        for (var i = 0; i < obj.remove.length; i++) {
            remove.push({ type: obj.type, name: obj.remove[i] });
        }
        User.update({_id: id} , { $pushAll:{ tags: add } }, function(err){
           if(err) throw err;
           User.update({_id: id} , { $pullAll: { tags: remove } }, function(err){
             if(err) throw err;
             console.log('ok');
             return true;
           });
        });
    }

所有函数都是在没有错误的情况下执行的,但是如果我转到mongo shell,我可以看到只有推送查询才能正常运行。我尝试了各种类型的查询而没有结果。任何人都可以帮助我理解为什么第二个查询不起作用吗?

编辑: 这是关于我的obj对象的结构,其中type是一个简单的字符串,add和remove是字符串数组。

var obj = {
   type: $rootScope.Modal.content,
   add: $rootScope.Modal.addCache,
   remove: $rootScope.Modal.removeCache
}

1 个答案:

答案 0 :(得分:0)

我通过更改嵌套查询解决了这个问题。

User.update({_id: id} , { $pushAll:{ tags: add } }, function(err){
        if(err) throw err;
        User.update({_id: id} , { $pull: { tags: { name: { $in: obj.remove } } } }, function(err){
            if(err) throw err;
        });
    });

现在效果还不错。