Home Web Front-end JS Tutorial How to solve the problem that unique setting in mongoose does not take effect

How to solve the problem that unique setting in mongoose does not take effect

Jan 19, 2018 pm 01:46 PM
unique how

This article mainly introduces to you the solution to the problem that unique settings in mongoose database do not take effect, as well as examples of how to remove unique restrictions in Mongoose. The article introduces it in detail through sample code. Friends who need it can refer to it. I hope Can help everyone.

Preface

unique is a member of schema constraint verification. Its main function is to make the value of a certain field unique (cannot be repeated)

To maintain the uniqueness of fields, use type values: {type:String,unique:true,dropDups: true}

Note: Once mongoose modifies the data storage mechanism, the database must be restarted. Many novices have this reason when setting some properties does not take effect

The restart mentioned here is not simply closing the mongoose database server and reopening it, but first deleting the entire database and then restarting the database service

Simple schema special usage example

//导入模块

var mongoose = require('mongoose');

//连接数据库
mongoose.connect('mongodb://localhost/itheima');

//创建schema

//schema第一个参数是我们自定义的数据类型 第二个参数是管理schema默认的数据类型
var studentSchema = mongoose.Schema({
 name:{type:String,required:true},//数据类型为string,不能非空
 age:{type:Number,default:18},//数据类型为string,默认值18
 study_id:{type:Number,select:true},//学号,默认查询字段
 address:{type:String,lowercase:true},//地址,默认小写
 email:{type:String,match:RegExp(/^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/)},//邮箱,正则表达式验证
 phone:{type:String,unique:true,dropDups: true}//电话号码唯一性
},{
  versionKey: false,//去掉版本锁 __v0

 timestamps: { createdAt: 'createTime', updatedAt: 'updateTime' }//自动管理修改时间

});

//创建model

var student = mongoose.model('student',studentSchema);

//创建Entity

var zhangsan = new student({
 name:'zhangsan',//名字必须要有,否则会报错: name: Path `name` is required.
 address:'ZhongLiang',//字符串都会变成小写
 email:'a12345@qq.com',//邮箱格式不对,添加会报错 Path `email` is invalid (a12345qq.com).
 study_id:2017001,
 phone:'123456789'//在添加唯一性字段时,mongoose会先查询数据库所有的phone值,一旦发现该值已存在则会报错
});

//添加数据



student.create(zhangsan,function(err){

 if(err){
  throw err;
 }

 console.log('插入成功' + zhangsan);

});
Copy after login

Mongoose removes unique restrictions

The email in the program initially set the unique restriction, resulting in emails that cannot be repeated in this collection Inserted, now want to remove the unique restriction.

db.your_collection.dropIndexes();
Copy after login

Related recommendations:

Two methods for mongoose to update objects

Detailed explanation of Mongoose’s virtual field query implementation method

Basic tutorial on installing and using Mongoose with Node.js to operate MongoDB_node.js

The above is the detailed content of How to solve the problem that unique setting in mongoose does not take effect. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Is there a future for employment in clinical pharmacy at Harbin Medical University? (What are the employment prospects for clinical pharmacy at Harbin Medical University?) Is there a future for employment in clinical pharmacy at Harbin Medical University? (What are the employment prospects for clinical pharmacy at Harbin Medical University?) Jan 02, 2024 pm 08:54 PM

What are the employment prospects of clinical pharmacy at Harbin Medical University? Although the national employment situation is not optimistic, pharmaceutical graduates still have good employment prospects. Overall, the supply of pharmaceutical graduates is less than the demand. Pharmaceutical companies and pharmaceutical factories are the main channels for absorbing such graduates. The demand for talents in the pharmaceutical industry is also growing steadily. According to reports, in recent years, the supply-demand ratio for graduate students in majors such as pharmaceutical preparations and natural medicinal chemistry has even reached 1:10. Employment direction of clinical pharmacy major: After graduation, students majoring in clinical medicine can engage in medical treatment, prevention, medical research, etc. in medical and health units, medical research and other departments. Employment positions: Medical representative, pharmaceutical sales representative, sales representative, sales manager, regional sales manager, investment manager, product manager, product specialist, nurse

Tips and FAQs on using unique indexes in MySQL Tips and FAQs on using unique indexes in MySQL Mar 15, 2024 pm 03:09 PM

Tips and FAQs for using unique indexes in MySQL MySQL is a popular relational database management system. In practical applications, unique indexes (uniqueindex) play a vital role in data table design. A unique index can ensure that the value of a certain column in the table is unique and avoid duplicate data. This article will introduce the usage skills of unique indexes in MySQL and answers to some common questions, and provide specific code examples to help readers better understand. 1.Create

How to download win10 image quickly How to download win10 image quickly Jan 07, 2024 am 11:33 AM

Recently, some friends reported how to download win10 image files. Because there are so many image files on the market, what should I do if I want to find a regular file to download? Today, the editor has brought you the link to download the image and the detailed solution steps. Let’s take a look at them together. win10 image quick download and installation tutorial download link >>> System Home Ghostwin101909 image 64-bit version v2019.11<<<>>>Win10 image 64-bit v2019.07<<<>>>Win10 image 32-bit v2019.07<< <1. Search through the Internet

How to clean temp folder How to clean temp folder Feb 22, 2024 am 09:15 AM

How to clean the temp folder As we use the computer, temporary files (temp files) will gradually accumulate. These temporary files are generated when we use the computer, such as cache files when browsing the web, temporary files during software installation, etc. Failure to clean the temp folder for a long time may occupy a large amount of disk space and affect the speed of the computer. Therefore, cleaning the temp folder regularly is a necessary step to maintain computer performance. Below, we will introduce some simple ways to clean the temp folder. Method 1: Manually clean t

How to reset Win10 system How to reset Win10 system Jun 29, 2023 pm 03:14 PM

How to reset Win10 system? Nowadays, many friends like to use computers with Win10 system. However, they will inevitably encounter some unsolvable problems when using computers. At this time, you can try to reset the system. So how should you do it? Let’s follow the editor to watch the tutorial on resetting the Win10 system. Users in need should not miss it. Tutorial on resetting the Win10 system 1. Click Windows and select Settings. 2. Click Update and Security. 3. Select Restore. 4. Click Start on the right to reset this computer. The above is the entire content of [How to reset Win10 system - Tutorial on resetting Win10 system]. More exciting tutorials are available on this site!

How to check win11 computer configuration How to check win11 computer configuration Jun 29, 2023 pm 12:15 PM

How to check win11 computer configuration? The win11 system is a very practical computer operating system version. This version provides users with rich functions, allowing users to have a better computer operating experience. So many friends who use computers are curious about their computers. Specific configuration, how to perform this operation in win11 system? Many friends don’t know how to operate in detail. The editor has compiled a tutorial on how to view the win11 computer configuration below. If you are interested, follow the editor and read on! Win11 computer configuration view tutorial 1. Click the windows icon on the taskbar below or press the "windows key" on the keyboard to open the start menu. 2. Find "Settings" or "sett" in the start menu.

Solve the problem of environment detection when reinstalling the system Solve the problem of environment detection when reinstalling the system Jan 08, 2024 pm 03:33 PM

How to solve the problem that the environment test fails when reinstalling the system and needs to be rewritten. The reason is: the mobile phone is poisoned. You can install anti-virus software such as Mobile Manager for anti-virus. 2. Many junk files are stored inside the mobile phone, causing the running memory of the mobile phone to be occupied. Just clear the phone cache to solve this problem. 3. The phone memory is occupied too much by saved software and files. It is no problem to delete unnecessary files and software frequently. As long as your hardware configuration meets the installation requirements, you can use the new one directly. Reinstall the system from the system disk! You can use a USB flash drive or hard disk to install, which is very fast. But the key is to use a system disk with good compatibility (supports installation in IDE, ACHI, and RAID modes), and it can be automatically and permanently activated, which has been verified. so

Unique index in MySQL database: usage and precautions Unique index in MySQL database: usage and precautions Mar 15, 2024 pm 04:06 PM

Unique index in MySQL database: usage and precautions MySQL is a very popular open source relational database management system that can be used to store and manage large amounts of data. In MySQL, we often use indexes to improve data retrieval and insertion efficiency. Among them, unique index is a special index type, which requires that the value of the index column must be unique in the entire table. This article will introduce the usage and precautions of unique index in MySQL database, and provide specific code examples.

See all articles