skip to Main Content

I am trying learn nodejs and stumble upon this error

TypeError: callback is not a function

and here is the code for my server.js

var mongoose = require('mongoose');
mongoose.createConnection('mongodb://localhost/fruitsDB',{useMongoClient:true}, { useNewUrlParser: true },{useUnifiedTopology: true},()=>{console.log('Connected')});

const fruitSchema = new mongoose.Schema({
    name: String,
    rating: Number,
    review: String
});

const Fruit = mongoose.model("Fruit", fruitSchema);
const fruit = new Fruit({
    name: "Apple",
    rating: 7,
    review: "Pretty good"
});

fruit.save();

and shows this error

TypeError: callback is not a function
at C:UserswinnedocumentsbackendfruitsProjectnode_modulesmongooselibconnection.js:826:21
at connectCallback (C:UserswinnedocumentsbackendfruitsProjectnode_modulesmongodblibmongo_client.js:527:5)
at C:UserswinnedocumentsbackendfruitsProjectnode_modulesmongodblibmongo_client.js:418:11
at processTicksAndRejections (node:internal/process/task_queues:78:11)

Node.js v17.8.0

can you tell me what’s wrong with my code that I got an error telling me callback isn’t a function?

2

Answers


  1. The options should be added in one single object when creating connection.

    let options = {
      useMongoClient: true,
    useNewUrlParser:true,
    }
    mongoose.createConnection(uri, options, callback)

    }

    you can checkout https://mongoosejs.com/docs/connections.html#options for the documentation too

    Login or Signup to reply.
  2. Options should all be passed in a single object like so:

    var mongoose = require('mongoose');
    const opts = {
        useMongoClient:true, 
        useNewUrlParser: true, 
        useUnifiedTopology: true
    }
    mongoose.createConnection('mongodb://localhost/fruitsDB', opts, ()=>{console.log('Connected')});
    
    const fruitSchema = new mongoose.Schema({
        name: String,
        rating: Number,
        review: String
    });
    
    const Fruit = mongoose.model("Fruit", fruitSchema);
    const fruit = new Fruit({
        name: "Apple",
        rating: 7,
        review: "Pretty good"
    });
    
    fruit.save();
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search