The provided namespace (database or collection name) is invalid
This error occurs when you try to create a collection or database with a name that contains invalid characters or does not follow MongoDB's naming rules. A namespace is the concatenation of the database name and collection name.
- 1Using the `
MongoDB 73 — The provided namespace (database or collection name) is invalid | errcodes.dev errcodes-dev character in a collection name - 2Attempting to create a collection with an empty string (`''`) as its name
- 3Using the null character (``) in a collection or database name
- 4Creating a collection name that is too long
An `insertOne` operation implicitly tries to create a collection with a `
// Collection names cannot contain '#x27;.
db.getCollection("invalid$name").insertOne({ doc: 1 });expected output
MongoServerError: Invalid collection name: invalid$name
Fix 1
Sanitize and Correct the Namespace
WHEN Creating collections or databases dynamically.
// Remove invalid characters before creating the collection.
const dirtyName = "my$collection";
const cleanName = dirtyName.replace(/$/g, ""); // "mycollection"
db.getCollection(cleanName).insertOne({ doc: 1 });Why this works
Ensure that any user-provided or dynamically generated names are sanitized to remove invalid characters before being used as collection or database names.
Fix 2
Adhere to Naming Restrictions
WHEN Manually naming collections and databases.
Why this works
Review MongoDB's naming restrictions in the documentation. Avoid special characters and ensure names are of a reasonable length and do not start with reserved prefixes.
✕ Use characters that have special meaning in other systems (like '/') thinking they will work
Different filesystems and systems have different reserved characters. Sticking to simple alphanumeric names with underscores or dashes is the safest approach for maximum compatibility.
Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev