乐闻世界logo
搜索文章和话题

How to set DB name and Collection name in Mongoose?

1个答案

1

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:

javascript
const 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:

javascript
const 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:

  1. Setting Database Name:
javascript
mongoose.connect('mongodb://localhost:27017/blogDatabase', { useNewUrlParser: true, useUnifiedTopology: true });
  1. Setting Collection Names for Articles and Comments:
javascript
const 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.

2024年6月29日 12:07 回复

你的答案