Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get collection name from a Mongoose model object

I have a mongoose model like so:

var mongoose = require("mongoose");
var Schema = mongoose.Schema;

let schema = new Schema({
    test: String
}, {
    collection: "test"
});

let model = mongoose.model("TestModel", schema);

How do I retrieve the collection name if in a callback I only have access to the "model" reference.

Expecting something like:

model.getCollectionName();
like image 877
Maxime Asselin Avatar asked Apr 10 '17 19:04

Maxime Asselin


People also ask

How does Mongoose name collection?

The first argument is the singular name of the collection your model is for. Mongoose automatically looks for the plural, lowercased version of your model name. Thus, for the example above, the model Tank is for the tanks collection in the database. Note: The .model() function makes a copy of schema .

Does Mongoose model create a collection?

Mongoose by default does not create any collection for the model in the database until any documents are created. The createCollection() method is used to create a collection explicitly.

What does .save return Mongoose?

The save() method is asynchronous, so it returns a promise that you can await on. When you create an instance of a Mongoose model using new, calling save() makes Mongoose insert a new document.

What does $Set do in Mongoose?

The $set operator replaces the value of a field with the specified value. The $set operator expression has the following form: { $set: { <field1>: <value1>, ... } } To specify a <field> in an embedded document or in an array, use dot notation.


1 Answers

Just use :

model.collection.collectionName

You also have a lot of usefull informations in model.collection such as collection options.

like image 126
Julien TASSIN Avatar answered Sep 30 '22 16:09

Julien TASSIN