Mongoose Query.prototype.regex()函数
Mongoose Query API.prototype.regex() method 在Mongoose API中用于对查询对象使用。它允许我们指定正则表达式。使用这个方法,我们可以编写正则表达式查询条件来获取结果集以满足我们的要求。这个方法帮助我们利用正则表达式的功能来匹配查询中的字符串模式。让我们通过一个示例来理解 regex() 方法。
语法:
query.regex( path, value );
参数: 此方法接受两个参数,如下所述:
- path: 用于指定字符串形式的集合中的路径名称。
- value: 用于指定正则表达式模式。
返回值: 此方法不返回任何值。
设置Node.js Mongoose模块:
步骤1: 使用以下命令创建一个Node.js应用程序:
npm init
步骤2: 创建NodeJS应用程序后,使用以下命令安装所需的模块:
npm install mongoose
项目结构: 项目的结构将会如下所示:
数据库结构: 数据库结构将会像这样,以下数据库存在于MongoDB中。
示例1:
以下示例演示了Mongoose连接regex()方法的基本功能。在此示例中,我们提取了名字字段以“ent2”结尾的文档。我们为name字段定义了正则表达式。
文件名:app.js
// Require mongoose module
const mongoose = require("mongoose");
// Set Up the Database connection
const URI = "mongodb://localhost:27017/geeksforgeeks"
const connectionObject = mongoose.createConnection(URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
const studentSchema = new mongoose.Schema({
name: { type: String },
age: { type: Number },
rollNumber: { type: Number },
});
const Student = connectionObject.model(
'Student', studentSchema
);
const query = Student.find()
query.regex("name", /ent2$/);
query.then(result => {
console.log(result)
})
运行程序的步骤: 在项目的根目录下执行以下命令来运行应用程序:
node app.js
输出:
[
{
_id: new ObjectId("63a4a9a207370cdcd1961b2c"),
name: 'Student2',
age: 18,
rollNumber: 176,
__v: 0
}
]
示例2: 下面的示例说明了Mongoose Connection的基本功能 regex() 方法。当我们提供一个参数时,我们必须在 where() 方法之后使用 regex() 方法,并且使用最近提供给 where() 方法的路径。
文件名:app.js
// Require mongoose module
const mongoose = require("mongoose");
// Set Up the Database connection
const URI = "mongodb://localhost:27017/geeksforgeeks"
const connectionObject = mongoose.createConnection(URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
const studentSchema = new mongoose.Schema({
name: { type: String },
age: { type: Number },
rollNumber: { type: Number },
});
const Student = connectionObject.model('Student', studentSchema);
const query = Student.find()
query.where('name').regex(/^St/);
query.exec((error, result) => {
if (error) {
console.log(error);
} else {
console.log(result);
}
})
运行程序的步骤: 从项目的根目录执行以下命令来运行应用程序:
node app.js
输出:
[
{
_id: new ObjectId("63a40a1065e8951038a391b1"),
name: 'Student1',
age: 30,
rollNumber: 9,
__v: 0
},
{
_id: new ObjectId("63a4a98407370cdcd1961b1a"),
name: 'Student3',
age: 33,
rollNumber: 178,
__v: 0
},
{
_id: new ObjectId("63a4a9a207370cdcd1961b2c"),
name: 'Student2',
age: 18,
rollNumber: 176,
__v: 0
}
]
参考链接: https://mongoosejs.com/docs/api/query.html#query_Query-regex