Home > database >  TypeError: callback is not a function node js
TypeError: callback is not a function node js

Time:04-20

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:\Users\winne\documents\backend\fruitsProject\node_modules\mongoose\lib\connection.js:826:21 at connectCallback (C:\Users\winne\documents\backend\fruitsProject\node_modules\mongodb\lib\mongo_client.js:527:5) at C:\Users\winne\documents\backend\fruitsProject\node_modules\mongodb\lib\mongo_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?

CodePudding user response:

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

CodePudding user response:

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();
  • Related