Recently i have started learning mongodb and started to make a simple application that will just display the data present in my database. Here’s the code:
var mongoose = require("mongoose"); mongoose.connect("mongodb://localhost/new_app",{ useNewUrlParser: true }); var familySchema = new mongoose.Schema({ name:String, age:Number, gender:String }); var family = mongoose.model("family", familySchema); family.create({ name: "Test", age: 17, gender: "Male" },function(err,member){ if(member){ console.log("Added Successfully"); } }); family.find({}, function(err,members){ if(members){ console.log(members); } });
After running this code, the data successfully gets stored in the database but it didn’t show me the output of all the data in my database. Can anyone explain how to fix this issue? Thanks in advance
Advertisement
Answer
Node uses non-blocking I/O and an asynchronous event-driven mode, so you should using async/await
const { func } = require("joi"); var mongoose = require("mongoose"); mongoose.connect("mongodb://localhost/new_app2",{ useNewUrlParser: true }); var familySchema = new mongoose.Schema({ name:String, age:Number, gender:String }); var family = mongoose.model("family", familySchema); async function run() { await family.create({name: "Test", age: 17, gender: "Male"}) let result = await family.find({}) console.log(result) } run()