2012-03-17 90 views
0

从mongo DB删除条目时遇到了一些问题。使用node-mongodb-native删除Mongo的条目

的代码有问题,IM是

ArticleProvider.prototype.delete = function(id, callback) { 
    this.getCollection(function(error, article_collection) { 
     if(error) callback(error) 
     else { 
     article_collection.findAndRemove({_id: article_collection.db.bson_serializer.ObjectID.createFromHexString(id)}, function(error, result) { 
      if(error) callback(error) 
      else callback(null, result) 
     }); 
     } 
    }); 
}; 

它的一个奇怪的问题,因为我有一个函数返回一个单品就是

ArticleProvider.prototype.findById = function(id, callback) { 
    this.getCollection(function(error, article_collection) { 
     if(error) callback(error) 
     else { 
     article_collection.findOne({_id: article_collection.db.bson_serializer.ObjectID.createFromHexString(id)}, function(error, result) { 
      if(error) callback(error) 
      else callback(null, result) 
     }); 
     } 
    }); 
}; 

和工程就像一个魅力

这是我的错误

500 TypeError: Cannot read property 'length' of undefined 
at Function.createFromHexString (/Users/username/express_blog/node_modules/mongodb/lib/mongodb/bson/objectid.js:226:22) 

它似乎是一个类型的id(或似乎)的问题。

回答

1

您传递的参数id必须是未定义的。

以下是该函数的当前版本的来源,或the newest one I could find on github

请注意,这里的框架代码不处理(typeof hexString === 'undefined')

ObjectID.createFromHexString = function createFromHexString (hexString) { 
    // Throw an error if it's not a valid setup 
    if(hexString != null && hexString.length != 24) throw new Error("Argument passed in must be a single String of 12 bytes or a string of 24 hex characters in hex format"); 

    var len = hexString.length; 

    if(len > 12*2) { 
    throw new Error('Id cannot be longer than 12 bytes'); 
    } 

    var result = '' 
    , string 
    , number; 

    for (var index = 0; index < len; index += 2) { 
    string = hexString.substr(index, 2); 
    number = parseInt(string, 16); 
    result += BinaryParser.fromByte(number); 
    } 

    return new ObjectID(result); 
}; 
+0

EHH,我讨厌愚蠢的错误,我想我是路过request.param.id时,它应该已经request.params.id ...谢谢! – 2012-03-17 21:16:35

+0

我知道这种感觉。我无法在github上提出pull请求,却没有意识到我在提交后搞砸了某些东西。 – dwerner 2012-03-17 21:18:45