Mongoose SchemaType.prototype.unique()函数
Mongoose是一个用于node.js环境的MongoDB对象建模和处理的库。 Mongoose SchemaType unique 属性允许我们在mongoose路径上创建唯一索引,以防止在文档中重复。让我们通过一些示例来更好地理解这一点。
创建node应用程序并安装Mongoose:
步骤1: 使用以下命令创建node应用程序:
mkdir folder_name
cd folder_name
npm init -y
touch main.js
步骤2: 在创建ReactJS应用程序后,使用以下命令安装必需的模块:
npm install mongoose
项目结构: 将会如下所示。
示例1: 在这个示例中,我们将在架构路径上创建一个唯一索引,email,以便用户无法保存具有相同电子邮件的文档。
文件名: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,
},
email: {
type: String,
unique: true
}
}, { strict: true });
const Person = mongoose.model('Person', personSchema);
const person1 = new Person({ name: 'John',
email: 'john@test.com' });
const person2 = new Person({ name: 'Doe',
email: 'john@test.com' });
(async function () {
await person1.save();
await person2.save(function (err) {
console.log(err)
});
const persons = await Person.find()
console.log(persons)
})()
运行应用程序的步骤: 使用以下命令从项目的根目录运行应用程序:
node main.js
输出:
示例2: 在这个示例中,我们将在模式路径“name”上创建一个唯一索引,以防止用户保存具有相同名称的文档。
文件名: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,
unique: true
},
email: {
type: String,
}
}, { strict: true });
const Person = mongoose.model('Person', personSchema);
const person1 = new Person({ name: 'John',
email: 'john@test.com' });
const person2 = new Person({ name: 'John',
email: 'doe@test.com' });
(async function () {
await person1.save();
await person2.save(function (err) {
console.log(err)
});
const persons = await Person.find()
console.log(persons)
})()
运行应用程序的步骤: 从项目的根目录中使用以下命令运行应用程序:
node main.js
输出:
参考: https://mongoosejs.com/docs/api/schematype.html#schematype_SchemaType-unique