How to use MongoDB for nodejs to modify the schema of an existing collection?

The function db.createCollection provided by the MongoDB module is difficult to use. It cannot modify the schema of a collection in an existing database.

How to use MongoDB for nodejs to modify the schema of an existing collection?

Once a collection has been created, use the collMod command to modify the validator for a collection. See Database Commands in the Node.js driver documentation for a general example of how to call a database command like collMod.

I couldn’t find an obvious example of modifying schema validation in the Node.js driver docs, so I created an improvement suggestion in the issue tracker which you can upvote & watch: NODE-2511: Add example for changing validator on an existing collection.

Note: the $jsonSchema query operator is also useful to test schema validation changes against existing documents. For an example using the mongo shell, see: How to find all invalid document based on jsonSchema validator?.

Regards,
Stennie

thanks for your help

client.db('dbName').command({collMod:'collectionName',{validator:{$jsonSchema:{ //your schema}, validationOptions}
make you sure you have a dbAdmin role , (in your user settings choose grant specific privileges and add dbAdmin and other roles you need , for example first role : dbAdmin and second: readWrite , and don’t forget to specify the database name )