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

How to get collection name from a Mongoose model object

1个答案

1

In Mongoose, each model object is associated with a collection name, which is typically derived from the plural form of the model name. To retrieve the collection name from a model object, you can access the collection property of the model object and then use collection.name to obtain the actual collection name. Here is a simple example:

javascript
const mongoose = require('mongoose'); // Define the model const Schema = mongoose.Schema; const someModelSchema = new Schema({ // Model definition }); const SomeModel = mongoose.model('SomeModel', someModelSchema); // Retrieve the collection name const collectionName = SomeModel.collection.name; console.log(collectionName); // Outputs the collection name, which is typically the plural form of the model name, e.g., "somemodels"

In this example, SomeModel is created based on someModelSchema. To retrieve the collection name for this model, we access SomeModel.collection.name, which returns the actual collection name stored in MongoDB.

Note that by default, Mongoose converts the model name to lowercase and appends a plural suffix to form the collection name. If you want to customize the collection name, you can pass it as the third parameter when defining the model:

javascript
const SomeModel = mongoose.model('SomeModel', someModelSchema, 'custom_collection_name');

In this case, the collection name will be 'custom_collection_name' instead of the automatically generated name based on 'SomeModel'.

2024年6月29日 12:07 回复

你的答案