Mongoose SchemaType.prototype.select()函数
Mongoose 是用于node.js环境的MongoDB对象建模和处理工具。 Mongoose SchemaType select属性 是一种SchemaType方法,它允许我们为mongoose模式中的特定路径设置默认的select()行为。让我们通过一些示例更加了解它。
创建node应用并安装Mongoose:
步骤1: 使用以下命令创建一个node应用:
mkdir folder_name
cd folder_name
npm init -y
touch main.js
步骤2: 创建了ReactJS应用程序后,使用以下命令安装所需模块:
npm install mongoose
项目结构:
它会如下所示。
示例1: 在这个示例中,我们将把名为路径的select属性设置为false,以便在数据库的日志中不包括这个路径的数据。
文件名: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 personSchema = new mongoose.Schema({
name: {
type: String,
select: false
},
email: {
type: String
}
});
const Person = mongoose.model('Person', personSchema);
const person1 = new Person({ name: 'John', email: 'john@test.com' });
const person2 = new Person({ name: 'Doe', email: 'doe@test.com' });
(async function () {
await person1.save();
await person2.save();
const persons = await Person.find()
console.log(persons);
})()
运行应用程序的步骤: 从项目的根目录中,使用以下命令来运行应用程序:
node main.js
输出:
示例2: 在这个示例中,我们将把名称路径的选择属性设置为true,但会在查询级别上覆盖此设置,将其改为false,从而不在数据库的日志中包括这条路径的数据。
文件名: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 personSchema = new mongoose.Schema({
name: {
type: String,
select: true
},
email: {
type: String,
}
});
const Person = mongoose.model('Person', personSchema);
const person1 = new Person({ name: 'John', email: 'john@test.com' });
const person2 = new Person({ name: 'Doe', email: 'doe@test.com' });
(async function () {
await person1.save();
await person2.save();
const persons = await Person.find().select('-name')
console.log(persons);
})()
运行应用程序的步骤: 从项目的根目录使用下面的命令运行应用程序:
node main.js
输出:
参考: https://mongoosejs.com/docs/api/schematype.html#schematype_SchemaType-select