Mongoose 模式查询助手
Mongoose 是一个用于node.js环境的MongoDB对象建模和处理工具。 Mongoose模式查询 助手 类似于Mongoose查询的实例方法。这些查询助手可用于过滤mongoose查询结果或对现有结果执行其他操作。
创建node应用并安装Mongoose:
步骤1: 使用以下命令创建一个node应用:
mkdir folder_name
cd folder_name
npm init -y
步骤2: 在创建ReactJS应用程序后,使用以下命令安装所需模块:
npm install mongoose
项目结构 :它将如下所示。
示例1: 在这个示例中,我们将创建一个查询助手,允许我们根据我们提供的动物类型来过滤文档。
文件名:main.js
const mongoose = require('mongoose')
// Database connection
mongoose.connect('mongodb://localhost:27017/query-helpers', {
dbName: 'event_db',
useNewUrlParser: true,
useUnifiedTopology: true
}, err => err ? console.log(err) :
console.log('Connected to database'));
const animalSchema = new mongoose.Schema({
name: String, type: String }, {
// Assign a function to the "query" object of our
// animalSchema through schema options.
// By following this approach, there is no need
// to create a separate TS type to define the
// type of the query functions.
query: {
byType(type) {
return this.where({ type })
}
}
}
);
const Animal = mongoose.model("Animal", animalSchema);
const animals = [
{
name: 'bond',
type: 'dog'
},
{
name: 'cevin',
type: 'cat'
}
]
Animal.insertMany(animals, (err, res) => {
Animal.find().byName('cat').exec((err, animals) => {
console.log(animals);
});
})
运行应用程序的步骤: 从项目的根目录中使用以下命令运行应用程序:
node main.js
输出:
示例2: 在这个示例中,我们将创建一个查询助手,允许我们通过输入的动物名称来筛选文档。
文件名:main.js
const mongoose = require('mongoose')
// Database connection
mongoose.connect('mongodb://localhost:27017/query-helpers', {
dbName: 'event_db',
useNewUrlParser: true,
useUnifiedTopology: true
}, err => err ? console.log(err) : console.log
('Connected to database'));
const animalSchema = new mongoose.Schema({
name: String, type: String }, {
// Assign a function to the "query" object of our
// animalSchema through schema options.
// By following this approach, there is no need
// to create a separate TS type to define the
// type of the query functions.
query: {
byName(name) {
return this.where({ name })
}
}
}
);
const Animal = mongoose.model("Animal", animalSchema);
const animals = [
{
name: 'bond',
type: 'dog'
},
{
name: 'cevin',
type: 'cat'
}
]
Animal.insertMany(animals, (err, res) => {
Animal.find().byName('bond').exec((err, animals) => {
console.log(animals);
});
})
运行应用程序的步骤: 在项目的根目录中使用以下命令运行应用程序:
node main.js
输出:
参考: https://mongoosejs.com/docs/guide.html#query-helpers