Arik Jordan Graham
Arik Jordan Graham

Reputation: 341

How to set DB name and Collection name in Mongoose?

I'm building a small program that connects to MongoDB-Atlas. I created a connection, a Schema, a Model and created a document. but somehow my DB name is "test" and Collection name is "users" without me defined it in the code or in Atlas, is that the default names? and how to create/rename a DB and a collection.

the code :

user.js

const mongoose = require('mongoose');
const SchemaObj = mongoose.Schema;
const userSchema = new SchemaObj({
    name : {
        type:String,
        require:true

    },
    email : {
        type:String,
        require:true
    },
    password: {
        type:String,
        require:true
    }
});

mongoose.model('User',userSchema);

app.js

const express = require('express');
const app = express();
const rout = express.Router();
const PORT = 8888;
const {connectionString} = require('./Keys');
const mongoose = require('mongoose');

app.use(express.json());
app.use(require('./routes/auth'));

app.get('/',(req,res)=>{
    console.log('succesfully connected');
    res.send('im in!');
});

let server = app.listen(PORT,'0.0.0.0',()=>{
    let FuncPort = server.address().port
    let host = server.address().address
    console.log("Example app listening at http://%s:%s", host, FuncPort)
});

const client = mongoose.connect(connectionString, {
  useNewUrlParser: true,
  useUnifiedTopology: true
});
    
mongoose.connection.on('connected',()=>{
    console.log('connected to mongodb oh hell yea');
});

mongoose.connection.on('error',()=>{
    console.log('error connecting to mongodb oh hell yea');
});

auth.js

const mongoose = require('mongoose');
const express = require('express');
const route = express.Router();
require('../moduls/User');
const user = mongoose.model("User");

rout.post('/sign',(req,res)=>{
    const {name,password,email} = req.body;
    if(name && password && email) {
        console.log('you god damn right!');
        res.json("you god damn right in response");
    } else {
        console.log('you are god damn wrong stupid idiot!');
        res.status(422);
        res.json("you are god damn wrong you stupid idiot in response");
    }

    user.findOne({email:email}).then((resolve,reject)=>{
        if(resolve)
            return res.status(422).json("user already exist yo");
        
        const newUser = new user({ name, email, password });
        newUser.save().then(() => {
            res.json('saved user!!!!');
        }).catch(err => {
            console.log("there was a problem saving the user")});
        }).catch(err => {  
            console.log(err);
        })
});
module.exports = route;

By the way, what is the difference between mongoose and MongoDB libraries?

Upvotes: 11

Views: 28700

Answers (5)

Mohammad Asadi
Mohammad Asadi

Reputation: 21

For naming your mongodb database and your collection after url , you can find the answer here:

mongoose.connect(
    "mongodb+srv://username:<password>@clustername.abc.mongodb.net/my-new-db-name?retryWrites=true&w=majority" ,
    {
        dbName: 'db-name',
    } ,
    { 
        collection: 'collection-name'
    }
).then(() => {
    console.log("Connected to Database");
}).catch((err) => {
    console.log("Not Connected to Database!");
})

Upvotes: 2

NGR
NGR

Reputation: 141

This is how I change my DB name

Before

mongodb+srv://username:<password>@clustername.abc.mongodb.net/?retryWrites=true&w=majority

after you get your API key you can add 1 more path (/) before the query (?) and that path will be your DB name automatically

the example: I add my DB name as

my-new-db-name

after

mongodb+srv://username:<password>@clustername.abc.mongodb.net/my-new-db-name?retryWrites=true&w=majority

Upvotes: 14

Soubhagya Kumar Barik
Soubhagya Kumar Barik

Reputation: 2595

Approach 1

const url = "mongodb://127.0.0.1:27017/DatabaseName"

mongoose.connect(url).then(() => {
    console.log("Connected to Database");
}).catch((err) => {
    console.log("Not Connected to Database ERROR! ", err);
});

Approach 2

const url = "mongodb://127.0.0.1:27017"

mongoose.connect(url,{
    dbName: 'DatabaseName',
}).then(() => {
    console.log("Connected to Database");
}).catch((err) => {
    console.log("Not Connected to Database ERROR! ", err);
});

Upvotes: 10

Mahfod
Mahfod

Reputation: 315

MONGODB_URI = mongodb+srv://name:@next.txdcl.mongodb.net/(ADD NAME DB)?retryWrites=true&w=majority

You can just add name what you want ( ADD NAME ) and delete test db and reloa

Upvotes: 6

Willian
Willian

Reputation: 3405

For naming your mongodb database, you should place it in your connection string, like:

mongoose.connect('mongodb://localhost/myDatabaseName');

For naming your collection or disabling pluralization, you can find the answer here:

What are Mongoose (Nodejs) pluralization rules?

var schemaObj = new mongoose.Schema(
{
 fields:Schema.Type
}, { collection: 'collection_name'});

Mongoose is an Object Data Modeling (ODM) library for MongoDB and Node.js. Similar to Sequelize (ORM) but for documents (NoSQL).

Upvotes: 19

Related Questions