【问题标题】:Optimal way of searching, and removing from an array in Mongoose在 Mongoose 中搜索和从数组中删除的最佳方式
【发布时间】:2012-01-06 01:42:35
【问题描述】:

我想知道我在快递中使用猫鼬的方式是否做错了什么。我的代码看起来不正确。在文档中添加内容需要 2 次 mongoose 查询,我想知道这是否可以简化。

所以这个函数会在我的快递路线中被引用,我该如何简化呢?它在集合中搜索用户通知文档,删除待处理数组中的某些内容并保存。我还想添加另外 2 个查询以查找用户接受的请求文档并在其中添加旧的待处理文档,但它会在一个请求中进行总共 4 个查询和一个循环......听起来不太对劲......

var acceptRequest = function(userId, requesterId, callback){

    NotificationsReference.findOne({ id: userId}, function(err, result){
        if(err || result === null){
            callback("Could not accept notification. Stack: " + err);
        }
        else{
            var deletedRefId = 'unchanged';
            for(i = 0; i < result.pending.length; i++){

               if( result.pending[i].refId = requesterId){
                   //Removing searched element of the array
                   deletedRefId = result.pending.splice(i, 1);
                   result.save(function (err) {
                   if (err) { 
                        callback("Error in saving request(2). Stack Trace: " + err); 
                    }
                    else{
                        callback("Success");
                    }

               }

            }

        }
    });

}

【问题讨论】:

  • 这么好的问题:-)

标签: javascript node.js mongodb express mongoose


【解决方案1】:

我有类似的问题,但现在我找到了解决方案。您可以从待处理数组中删除项目,只需对其调用 remove 函数,猫鼬数组实现:http://jsdoc.info/SirUli/mongoose/types%7Carray.html#instance/remove

var acceptRequest = function(userId, requesterId, callback){

NotificationsReference.findOne({ id: userId}, function(err, result){
    if(err || result === null){
        callback("Could not accept notification. Stack: " + err);
    }else{
        var deletedRefId = 'unchanged';
        result.pending.remove(requesterId)
        result.save(callback(err))
    }
});
}

【讨论】:

    【解决方案2】:

    如果您想查找和更新某些内容,总是有两个请求 :-) 您可以尝试通过 populate 添加对 NotificationsReference 的用户引用,并在获得 NotificationsReference 时对其进行修改。

    【讨论】:

      猜你喜欢
      • 2015-04-30
      • 2019-08-14
      • 2021-07-31
      • 2010-10-12
      • 1970-01-01
      • 2013-05-10
      • 2017-12-25
      • 2015-07-23
      • 2016-11-22
      相关资源
      最近更新 更多