I'm new on NodeJs, I'm learning how to connect to mongodb using NodeJS with Mongoose library. As I know, when I connect to database with a name, if this database with that name doesn't exist, then mongoose will create it automatically, but it's not being created with me. Here is my code:
const mongoose = require("mongoose");
mongoose.connect("mongodb://127.0.0.1:27017/mongo-test", {useNewUrlParser: true})
.then(() => console.log("Connected"))
.catch(err => console.log(err));
mongoose version: ^5.2.5
Creating a DatabaseMongoDB will create the database if it does not exist, and make a connection to it.
The first argument is the singular name of the collection that will be created for your model (Mongoose will create the database collection for the above model SomeModel above), and the second argument is the schema you want to use in creating the model.
Here mongoose will check if there is a collection called "Users" exists in MongoDB if it does not exist then it creates it. The reason being, mongoose appends 's' to the model name specified. In this case 'User' and ends up creating a new collection called 'Users'.
My understanding on the official documentation is that generally when there is only one connection mongoose. connect() is use, whereas if there is multiple instance of connection mongoose. createConnection() is used.
Pedro is right, when you save your first document in the database, mongoose will create the database and the collection for this document.
The name of the database will be the name specified in the connection, in this case myapp:
mongoose.connect('mongodb://localhost:27017/myapp');
Mongoose Documentation: Connections
And mongoose creates the collection with a plural name.
If you have a model with Tank name, the collection name will be tanks:
var schema = new mongoose.Schema({ name: 'string', size: 'string' });
var Tank = mongoose.model('Tank', schema);
The first argument is the singular name of the collection your model is for. Mongoose automatically looks for the plural version of your model name. Thus, for the example above, the model Tank is for the tanks collection in the database.
Mongoose Documentation: Model
I'm not 100% sure but you also need to create a record so that it creates the database. Only specifying the database name on the connection string isn't enough apparently.
Cheers
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With