我在从mongo DB中删除条目时遇到了一些问题。我正在使用node-mongodb-native
有问题的代码是
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类型的问题(或似乎)。
答案 0 :(得分: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);
};