我通过将字符串转换为BSON来进行MongoDB查找.在进行转换之前,有没有办法让我确定我拥有的字符串是否是Mongo的有效ObjectID?
这是我当前findByID函数的coffeescript.它工作得很好,但如果我确定字符串不是ID,我想通过不同的属性进行查找.
db.collection "pages", (err, collection) ->
collection.findOne
_id: new BSON.ObjectID(id)
, (err, item) ->
if item
res.send item
else
res.send 404
Run Code Online (Sandbox Code Playgroud) 参考这个 SO问题,我有一个场景,我只需要匹配包含af的十六进制字符串.其他一切都不匹配.例:
checkForHexRegExp.test("112345679065574883030833"); // => false
checkForHexRegExp.test("FFFFFFFFFFFFFFFFFFFFFFFF"); // => false
checkForHexRegExp.test("45cbc4a0e4123f6920000002"); // => true
Run Code Online (Sandbox Code Playgroud)
我的用例是我正在使用一组十六进制字符串,并且只想验证那些是mongodb objectID的真实.
我创建了一个这样的C#类:
public class Employee
{
[BsonRepresentation(BsonType.ObjectId)]
public string Name { get; set; }
public int Age { get; set; }
public List<string> Address { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
当我尝试保存此信息(使用MongoDB)时,如下所示:
var e = new Employee();
e.Address = new List<string>();
e.Address.Add("Address 1");
e.Address.Add("Address 2");
e.Age = 333;
e.Name = "Some Name";
context.Employees.Insert(e);
Run Code Online (Sandbox Code Playgroud)
我收到以下错误:
An unhandled exception of type 'System.FormatException' occurred in MongoDB.Bson.dll
Additional information: 'Some Name' is not a valid 24 digit hex string.
Run Code Online (Sandbox Code Playgroud)
如何使字符串字段ObjectID在MongoDB中起作用?
有没有办法验证 MongoDB ObjectId而不实际访问 MongoDB 数据库?例如,字符串值"5c0a7922c9d89830f4911426"应该导致"true".
我正在尝试按用户名或_id这样查找
exports.getUser = function (req, res){
User.find({ $or: [ {username:req.params.id}, {_id:req.params.id} ] })
.exec(function (err, collections) {
res.send(collections);
});
};
Run Code Online (Sandbox Code Playgroud)
当我通过_id搜索但是用户名失败时它会起作用,因为它无法返回有效的OjectID.我试着像这样做两个单独的查询
exports.getUser = function (req, res){
User.findOne({username:req.params.id}).exec(function (err, user) {
if (user)
res.send(user);
});
User.findById({_id:req.params.id}).exec(function (err, user) {
if (user)
res.send(user);
});
};
Run Code Online (Sandbox Code Playgroud)
但如果用户不存在,则会挂起,因为它从不发送响应.由于节点是异步的,我得到,Error: Can't set headers after they are sent.如果我添加
else
res.sendStatus(400);
Run Code Online (Sandbox Code Playgroud)
到findById查询.我想不出任何其他方法来解决这个问题.我在MongoDB Node中检查了正则表达式,检查objectid是否有效
exports.getUser = function (req, res){
var checkForHexRegExp = new RegExp("^[0-9a-fA-F]{24}$");
if(checkForHexRegExp.test(req.params.id)){
User.findById({_id:req.params.id}).exec(function (err, user) {
if (user)
res.send(user);
});
} …Run Code Online (Sandbox Code Playgroud)