How to add a document to a specific database AND collection in the URI

What’s the correct way to add a document to a specific mongodb database in the uri? I added <database=wdntestdb> in the uri but that did not add the item to the correct database. It added the item to a database that I deleted previously. I’m using nextjs and mongoose. The database is named “wdntestdb”.
//env.local:
MONGODB_CONNECTION_STRING = mongodb+srv://<USER_NAME>:@.mongodb.net/?retryWrites=true&w=majority&database=wndtestdb"

//Mongoose model
const AdminUser = models.AdminUser Schema || model('AdminUser ', AdminUserSchema, ‘AdminUsersCollection’);

Hi @david_h and welcome in the MongoDB Community :muscle: !

“database” isn’t a valid connection string option. You can set the default authentication DB like this:

mongodb+srv://<USER_NAME>:<PASSWORD>@abcde.mongodb.net/AuthDBhere?retryWrites=true&w=majority

But that’s it and you shouldn’t rely on this to write in the DB of your choice anyway.
Just use this to get to the right place.

const database = client.db("sample_mflix");
const movies = database.collection("movies");

Cheers,
Maxime.

2 Likes

Thank you. It seems that using the Mongdb client directly is a better option considering the Mongoosejs documentation does not offer an obvious, compatible way of achieving this. The only thing I would miss is the ability to use models? Also, how would I do data validation on the backend. Using mongoose I can do the following:

const AdminSchema = new Schema(

    {

        name: {type: String, trim: true, required: true},

        email: {type: String, trim: true, required: true, unique: true, lowercase: true},

        password: {type: String, required: true, minlength: 8}

    }

)

You can definitely write to multiple databases and collection with both the MongoDB Node.js driver and Mongoose. See the doc for both but it’s 100% sure you can with both.

Mongoose is an extra layer on top of the MongoDB Node.js driver though. I’m not a fan as I prefer to use directly the driver and all the features, but it’s your choice. Mongoose helps to enforce a schema as you have to work with models, but MongoDB is schemaless by design so nothing forces you to enforce a model / schema by default.

That being said, if you need or want to enforce some constraints, there are a couple of ways to do so:

  • In the back-end
  • In MongoDB

If you do so in the back-end (like by using Mongoose or some other JSON schema modules), you can’t guarantee that another client (=back-end) or direct command lines sent to the cluster will respect these constraints.

The only wait to enforce a constraint for sure, is to enforce it with the $jsonSchema directly in the MongoDB collection in the validator.

Read this for more details:

Cheers,
Maxime.

2 Likes

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.