When using Mongoose for MongoDB database development, setting the database (DB) name and collection (Collection) name is a fundamental and critical step. Here is a detailed explanation of how to configure them:
Setting Database Name
Database names are typically specified during the connection to MongoDB. You can define the database name using the URL parameter of Mongoose's connect method. For example:
javascriptconst mongoose = require('mongoose'); mongoose.connect('mongodb://localhost:27017/myDatabaseName', { useNewUrlParser: true, useUnifiedTopology: true });
In this example, myDatabaseName represents the database name you have configured.
Setting Collection Name
Collection names can be explicitly defined when creating models using Mongoose model options. If not specified, Mongoose automatically uses the plural form of your model name as the collection name. However, to customize the collection name, you can set it via the collection option when defining the model. For example:
javascriptconst mySchema = new mongoose.Schema({ name: String, age: Number }, { collection: 'customCollectionName' }); const MyModel = mongoose.model('MyModel', mySchema);
In this example, despite the model name MyModel, the collection name is set to customCollectionName using { collection: 'customCollectionName' }.
Practical Application Example
Suppose you are developing a blog system requiring a database and two collections: one for articles and another for comments. Here is how to configure them:
- Setting Database Name:
javascriptmongoose.connect('mongodb://localhost:27017/blogDatabase', { useNewUrlParser: true, useUnifiedTopology: true });
- Setting Collection Names for Articles and Comments:
javascriptconst articleSchema = new mongoose.Schema({ title: String, content: String, author: String }, { collection: 'articles' }); const commentSchema = new mongoose.Schema({ articleId: mongoose.Schema.Types.ObjectId, content: String, commentator: String }, { collection: 'comments' }); const Article = mongoose.model('Article', articleSchema); const Comment = mongoose.model('Comment', commentSchema);
By following this approach, you can precisely control your data structure and ensure it aligns with your application architecture requirements.