Reputation: 33
I am learning node js and mongoDb. I am trying to insert data using mongoose but while inserting it show error db is not defined. i am not able to figure out mistake. I have tried all my solution as i could try as a beginner.
var mongoose = require("mongoose"); // require mongoose
mongoose.connect('mongodb://localhost:27017/mydatabase', {useNewUrlParser: true});
const myConnection = mongoose.connection;
// Create Schema
var employeeSchema = new mongoose.Schema({
name: String,
email: String,
eType: String,
hourRate: Number,
totalHour: Number,
});
employeeSchema.methods.totalSalary = function () {
var total = employee.hourRate * employee.totalHour;
console.log(`total Salary is = ${total}`);
};
var employeeModel = mongoose.model("Employee", employeeSchema);
var employee = new employeeModel({
name: "Akash Jangra",
email: "[email protected]",
eType: "Hourly",
hourRate: 500,
totalHour: 70,
});
// console.log(employee)
employee.totalSalary();
myConnection.on('Connect', function(){
console.log('Connected Successfully')
});
myConnection.on('disconnect', function(){
console.log('Disconnected')
})
myConnection.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
// we're connected!
employee.save(function(err, res) {
if (err) throw error
console.log(res)
myConnection.close()
})
]1
Upvotes: 0
Views: 140
Reputation: 351
I think you're referring to the wrong variable here.
myConnection.once
should work. You have not declared db
anywhere in your code.
Upvotes: 1