walters
walters

Reputation: 27

mongoose.connect() is not creating a database?

I am using mongoose.connect() method but it couldn't created a DB ,i did even insert some documents in db by using insertMany() but it neither giving me any error nor creating a DB as when i checked my mongo Shell todolistDB is not created .

const express = require('express')
const bodyParser = require('body-parser')
const mongoose = require('mongoose')
mongoose.connect('mongodb://localhost:27017/todolistDB', {
        useNewUrlParser: true,
        useUnifiedTopology: true },
    function (err) {
        if (err) {
            console.log(err);
} else {console.log('server is connected');}})
const itemsSchema = mongoose.Schema({name: {type: String,required: true }})
const Item = mongoose.model('Item', itemsSchema)
const item1 = new Item({name: 'Welcome to your todo list!'})
const item2 = new Item({name: 'Hit + button to add new item'})
const item3 = new Item({name: '<-- click to delete a item!'})
const defaultItems = [item1, item2, item3]

app.get('/', function (req, res) {

Item.find({}, function (err, result) {

        if (defaultItems.length===0) {
                                          **even after insertmany method todolistDB is not created**
Item.insertMany(defaultItems, function (err) {   
                if (err) {
                    console.log(err);
                  } else {
                    console.log('new record inserted successfully!');}});
        } else {
            res.render('list', {listTitle: 'today',latestItems: result}) }

** when I used insertMany outside app.get() method then all records was inserted, I just started learning mongoDB sorry in advanced if it was a silly mistake ** detailed answer would be appreciated!

Upvotes: 0

Views: 190

Answers (3)

Shuvro
Shuvro

Reputation: 242

You Can Follow This Code

mongoose.connect('mongodb://localhost:27017/todolistDB', {
  useNewUrlParser: true,
  useUnifiedTopology: true,
  useCreateIndex: true,
  useFindAndModify: false
})

mongoose.connection.on("connected", () => {
  console.log("Mongodb connected")
})

mongoose.connection.on("error", errMsg => {
  console.log("Error connecting database. Msg: " + errMsg)
})

Upvotes: 0

D. SM
D. SM

Reputation: 14520

Consider the following three lines of your code:

[1] const defaultItems = [item1, item2, item3]

[2] Item.find({}, function (err, result) {

[3] if (defaultItems.length===0) {

In [2] you are doing a query, presumably it returns no results and you get to [3]. However in [3] you are referencing the fixed set defined in [1] which is of length 3. Thus the if statement in [3] is never entered.

Upvotes: 1

user11244871
user11244871

Reputation: 1

The code is pretty fine.

mongoose.connect() call is fine. Since you are writing it in Promise form, issue is Unhandled Promise Rejection for connection failure.

Console the error, the error message would give us better glimpse.

Coming to the error possibilities, it is likely to happen if you use middleware handler app.use or router.use.

Please console the error, drop down the error message. So that I can help you further.

Upvotes: 0

Related Questions