用于Number类型字段的Mongoose find()RegExp [英] Mongoose find() RegExp for Number type field
问题描述
我正在尝试创建一个带有过滤器的表,当我需要通过正则表达式查找行时,下面将出现错误. 我如何将RegExp与Number的字段类型一起使用?更改String的字段类型,是个好主意吗?
I'm try to create a table with filters and when i need find rows through regular expression i have error below. How i can use RegExp with field type of Number? Change field type on String, is a good idea?
var ContractSchema = new Schema({
userId: {type: Schema.Types.ObjectId, ref: 'User'},
number: Number,
// ...
});
module.exports = mongoose.model('Contract', ContractSchema);
Contract.find({number: /555/}, function(err, contracts){
console.log(err, contracts);
});
在路径数字"上对值"/555/"的广播到数字失败
Cast to number failed for value "/555/" at path "number"
推荐答案
当然,正则表达式仅适用于字符串.但是,您仍然可以这样做,尽管这样做效率很低:
Well regular expressions only work on strings of course. You could however still do this, though it's highly inefficient to do so:
Contract.find(
{ "$where": "function() { return this.number.toString().match(/555/) != null; }" }
).function(err,contracts) {
// do something with results
});
MongoDB $where
查询运算符允许在服务器上针对集合中的每个文档或其他查询条件遗留的文档评估JavaScript条件.
The MongoDB $where
query operator allows for a JavaScript condition to be evaluated on the server for each document in the collection or those left from other query conditions.
基本上,该评估将字段值转换为String
,然后对其进行正则表达式操作.
Basically that evaluation converts the field value to a String
and then allows a regex operation on it.
否则,您将更改内容或为字符串表示形式添加另一个字段.但是,除非您从字符串的开头使用锚点^
,否则即使在实际的字符串字段上执行$regex
操作,也比使用所示的JavaScript评估效率更高.
Otherwise, you change your content or add another field for a string representation. But unless you are using an anchor ^
from the start of the string, then even a $regex
operation on an actual string field is barely more efficient than using the JavaScript evaluation as shown.
P.S确保您的服务器允许JavaScript评估.有些人选择关闭此功能.但是默认情况下它应该是打开的.
P.S Make sure your server allows JavaScript evaluation. Some people choose to turn this off. But it should be on by default.
这篇关于用于Number类型字段的Mongoose find()RegExp的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!