mongodb-nodejs-driver

How to get the schema validator from a mongodb collection using node.js driver?


Is there a ways to get the current schema validator from an existing collection in mongodb 5? I want to write schema migration script for an existing schema by retrieving the current schema validator, adding the changes and updating it with

db.command({
  collMod: collectionName,
  validator: schema,
});

Mongo shell (mongosh) provides db.getCollectionInfos({name: "<collection_name>"})[0].options.validator to get the schema validator. However, there seems to be nothing equivalent in node.js driver to get the validator. Not sure why but it looks like this is by design.


Solution

  • I found the following solution. Are there any other solutions?

      const collection = await db.command({
        listCollections:1.0,
        filter: {name: '<collection_name>'}
      });
    
      let schema = collection.cursor.firstBatch[0].options.validator;