How do i fix this error i am not using MongoDb Atalas i want to use it in my local machine
const express = require('express');
const app = express()
const mongoose = require('mongoose');
const url = 'mongodb://localhost:27017/testDb'
mongoose.connect(url, {useNewUrlParser: true, useUnifiedTopology: true})
.then(() => console.log('DB Connected'))
mongoose.connection.on('error', err => {
console.log(`DB connection error: ${err.message}`)
});
const NewSchema = new mongoose.Schema({
name:String,
age:Number
})
const newModel = new mongoose.model("collection",NewSchema)
const data = newModel({
name:"prajwal",
age:30
})
data.save()
app.listen(3000,()=>{
console.log("listening to the port 3000")
})
This is the error that i got from the code
CodePudding user response:
The save()
call should be await
ed. Also, looks like you are not connected to the DB, try with:
const express = require('express');
const app = express();
const mongoose = require('mongoose');
const url = 'mongodb://localhost:27017/testDb';
const NewSchema = new mongoose.Schema({
name: String,
age: Number,
});
const newModel = new mongoose.model('collection', NewSchema);
(async () => {
try {
await mongoose.connect(url, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
console.log('DB Connected');
const data = newModel({
name: 'prajwal',
age: 30,
});
await data.save();
} catch (err) {
console.log(`DB connection error: ${err.message}`);
}
})();
app.listen(3000, () => {
console.log('listening to the port 3000');
});