Mongo Schema using NodeJS

hay i am trying to move from mongoose to the mongo driver and i want to make a schema for my user collection and i need to make a unique fields the schema i want to build is

Users={
   username: string ,unique,
   email:string ,unique,
   password,string,
   nickname:string,
}

Hello.

There is no defining of “schema” using the MongoDB NodeJS Driver, as you do using Mongoose ODM. When you insert a document into a collection it is created with the fields you had provided with the insert method. As such, you can insert documents with different schemas within the same collection - this is due to the nature of Flexible Schema of MongoDB documents. But, you can introduce Schema Validation for insert and update operations for a collection; this is an option.


This can be achieved by creating a Unique Index on the field(s). From the documentation:

A unique index ensures that the indexed fields do not store duplicate values; i.e. enforces uniqueness for the indexed fields. By default, MongoDB creates a unique index on the _id field during the creation of a collection.

does the index need to be specify through the shell or i can do it from my backend (NodeJS)?

does the index need to be specify through the shell or …

Preferably using the mongo shell - It is a good practice to do all data definition activities (these come under database administration) from the mongo shell. Of course, you can use NodeJS program or even a GUI tool like MongoDB Compass.