Home > database >  Why does MongoDB throw error "ns does not exist"?
Why does MongoDB throw error "ns does not exist"?

Time:05-21

I don't understand why MongoDB triggers an error with the following NodeJS code:

import {
  Collection,
  Document,
  Filter,
  IndexDirection,
  MongoClient,
  ObjectId
} from "mongodb";

export const client = new MongoClient(process.env.DB_URL);
await client.connect();
export const database = client.db(process.env.DB_NAME);
await database.command({ ping: 1 });

const users = database.collection("User");
console.log({ count: await users.countDocuments() }); // prints 0

await database.command({
  collMod: "User",
  validator: {
    $jsonSchema: {
      bsonType: "object",
      required: ["_id", "email"],
      additionalProperties: false,
      properties: {
        _id: { bsonType: "objectId" },
        email: { bsonType: "string" }
      }
    }
  },
  validationLevel: "strict"
}); // triggers error

The last instruction triggers the following error:

MongoServerError: ns does not exist

I understand that it comes from the fact that the collection doesn't exist, but shouldn't it exist by the time command is called? Thanks!

CodePudding user response:

I would vote that await users.countDocuments() returns 0 as workaround, effectively what happens here is:

  1. ns not found exception is thrown.
  2. This exception is handled by returning 0 without actual exception.

You can see it in the shell as well:

MongoDB Enterprise replset:PRIMARY> use notexisteddb
switched to db notexisteddb
MongoDB Enterprise replset:PRIMARY> db.coll.count()
0
MongoDB Enterprise replset:PRIMARY> show collections
MongoDB Enterprise replset:PRIMARY>
  • Related