2

I cant create my database 'sms-dev' in mongodb after starting the server but in my console it was printing connected to mongo successfully.I kept my db module inside models folder as db.js and export that module in another file(config.js) inside models folder

Here is the code in db.js file

 var db = {
   // Connects to mongoDB
   connect: function(url, options) {
   mongoose.connect(url, options);
   mongoose.connection.on('open', function(){
  console.log("Connected to mongo successfully");
  });

 mongoose.connection.on('disconnect', function(){
  console.log("Mongo disconnected");
});

mongoose.connection.on('error',function (err) {
  console.log('Mongoose default connection error: ' + err);
});

process.on('SIGINT', function() {
  mongoose.connection.close(function () {
    console.log('Mongoose default connection disconnected through app termination');
    process.exit(0);
  });
});

}
}

module.exports = db;

and my config.js file is

exports.database = {
  url: 'mongodb://127.0.0.1:27017/sms-dev',
  options: {
    db: { native_parser: true,safe:true },
    server: { poolSize: 10 }
   }
   }

I connected this db in server.js as

var dbcon = process.env.MONGOLAB_URI || config.database.url;
db.connect(dbcon, config.database.options);

8 Answers 8

3

This line:

As soon as you create a record with that connection

From this answer.

Did it for me. In my case I had to manually:

  • Create the database
  • Create a collection
  • Create a record in the collection

And then everything was good again.

Sign up to request clarification or add additional context in comments.

Comments

0

You should keep your db connection very simple as you are using mongoose. mongoose.connect should only be called once. That will create the default connection pool for your application.

//db.js

// Bring Mongoose into the app 
var mongoose = require( 'mongoose' ); 

// Create the database connection 
mongoose.connect('mongodb://127.0.0.1:27017/sms-dev'); 

// CONNECTION EVENTS
// When successfully connected
mongoose.connection.on('connected', function () {  
  console.log('Mongoose default connection open to ' + 'mongodb://127.0.0.1:27017/sms-dev');
}); 

// If the connection throws an error
mongoose.connection.on('error',function (err) {  
  console.log('Mongoose default connection error: ' + err);
}); 

// When the connection is disconnected
mongoose.connection.on('disconnected', function () {  
  console.log('Mongoose default connection disconnected'); 
});

// If the Node process ends, close the Mongoose connection 
process.on('SIGINT', function() {  
  mongoose.connection.close(function () { 
    console.log('Mongoose default connection disconnected through app termination'); 
    process.exit(0); 
  }); 
}); 

You can then easily use the db connection by require mongoose in your files.

//users.js

var mongoose = require( 'mongoose' ),  
    Users = mongoose.model('users'); 

6 Comments

Julien still i does not creating a database in mongo shell..i think i need to conect the db in server using this line in server.js var dbcon = process.env.MONGOLAB_URI || config.database.url; db.connect(dbcon, config.database.options);
Remove your options from your config.js and connect directly using 'mongodb://127.0.0.1:27017/sms-dev'. is the problem still there ? Can you please copy and past the logs you see on the terminal from node?
Getting error as..Mongoose default connection disconnected Mongoose default connection error: MongoError: connect ETIMEDOUT
Looks like mongo is not running. What do you see when you run mongod or sudo lsof | grep mongod | grep TCP ?
After printing mongod getting like tiz..2016-02-04T10:32:27.673+0530 I JOURNAL [initandlisten] journal dir=C:\data\db\journal 2016-02-04T10:32:27.675+0530 I JOURNAL [initandlisten] recover : no journal files present, no recovery needed 2016-02-04T10:32:27.679+0530 I JOURNAL [durability] Durability thread started 2016-02-04T10:32:27.680+0530 I JOURNAL [journal writer] Journal writer thread started
|
0

It seems that my mongodb was not locked properly so i remove the mongodb.lock file and run with -repair option

Comments

0

Once you ll save data in the database ,You can see the Database by running command

show dbs 


const mongoose=require("mongoose")
mongoose.connect('mongodb://localhost:27017/username_db');
var db=mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
  console.log("connected successfully")
});
const Schema=mongoose.Schema;
const myschema=new Schema({
    name:String,
},{
    timestamps:true
});

var model=mongoose.model('myname',myschema);
 var data=new myname({
            name: 'xyz',
          })
          data.save((err)=>{
            res.send("Error in saving to database");
          })

Comments

0

Once you ll save data in the database ,You can see the Database by running command

show dbs

const mongoose=require("mongoose")
mongoose.connect('mongodb://localhost:27017/username_db');
var db=mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
  console.log("connected successfully")
});
const Schema=mongoose.Schema;
const myschema=new Schema({
    name:String,
},{
    timestamps:true
});

var model=mongoose.model('myname',myschema);
 var data=new myname({
            name: 'xyz',
          })
          data.save((err)=>{
            res.send("Error in saving to database");
          })

Comments

0

This is quite old Post, to which I am updating using latest packages - This solution will fix this mongo db connection issue on following version of env.

  1. Node version - 11.5.0 (node -v)
  2. NPM. - 6.4.1(npm -v)
  3. Typescript. - 3.8.3(tsc -v)
  4. Mongodb. - 5.9.15 (package.json)

Following are the steps need to take care in order to fix this - 1. First of all verify all changes in .ts file will be reflecting changes in corresponding .js file. As it was issue with my code it was not being updated. Run following command and verify .js file

tsc --build tsconfig.json

If js file is not being updated simply delete.js file and run above command. It's pretty simple fix but some time we overlook for it.

  1. Since it's typescript code. So need to copy past below code for verification.

    Import * as m from 'mongoose';

    export class UserControl { RegisterUser(){ Const uri = "mongodb://127.0.0.1:27017/User"; m.connect(uri, {useNewUrlPaerser:true, useUnifiedTopology:true, useFindAndModify:true, useCreateIndex:true });

        Let db = m.connection;
    
        Db.once("open",async() =>. 
       {console.log(connected)});
    
        Db.once("error",async() =>
         {console.log(error)});
    
         Const userSchema = new m.schema({
                                                      FirstName:string,
                                                      Last name:string
                                                    });
    
         Const User = m.model('users', userSchema);
         Const user = new User({
                                           FName:Andy,
                                           LName:Pat });
    
         Const result = await user.save();
         Console.log(result);
    

    }

  2. Run your solution by npm start. Verify if db collection created?

If not. First create db with name as "User" in mongodb Using mongo db compass.

And than try. Still not able to see the collection.

  1. Now need to start two separate console terminal.

    • go to folder and executive mongo c:\program file\MongoDb\server\4.2\bin> mongo.exe

    • on another terminal type mongod , it will start your mongo Damon.

Now try. Since this above step will stable connection and show 1 connection active.

Hope this update help.

Comments

0

If you are using Mongoose or MongoClient to connect the mongodb database you will see the database created after you save the first document to the database.

e.g.: the below code will only show connection was successful but it does not create the database 'mydb'

const mongoose = require('mongoose');

mongoose.connect('mongodb://localhost/mydb')
    .then(() => console.log('Connected to MongoDB...'))
    .catch(err => console.error('Could not connect to MongoDB...', err));

The databse 'mydb' is created only when you save first document record.

const courseSchema = new mongoose.Schema({
    name: String,
    author: String,
    tags: [String],
    date: {type: Date, default: Date.now},
    isPublished: Boolean
});

const Course = mongoose.model('Course', courseSchema);

async function createCourse(){
    const course = new Course({
        name: 'Some Course',
        author: 'My Name',
        tags: ['JavaScript', 'backend'],
        isPublished: true
    });    
    const result = await course.save();
    console.log(result);
}

createCourse();

Comments

-1

This is a duplicate of:

Mongo db that does not exist but shows up in connection

If you insert data your database will be created.

1 Comment

This is a completely different issue.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.