I am currently following Colt's Web Dev bootcamp and I have encountered an issue. In his version, everything works perfectly fine but when I use the same code, a new entry is added to the database, however, it is not displayed in the printed items unless I rerun the code.
My question is, why is the .find method running before the .create method and is there a way to prevent this?
This is the JavaScript code snippet:
const mongoose = require("mongoose");
mongoose.connect("mongodb://localhost:27017/catapp",
{
useNewUrlParser: true,
useUnifiedTopology: true
}
)
.then(() => console.log('Connected to DB!'))
.catch(error => console.log(error.message));
let catSchema = new mongoose.Schema({
name: String,
age: Number,
temperament: String
});
let Cat = mongoose.model("Cat", catSchema);
Cat.create ({
name: "Snow White",
age: 15,
temperament: "Bland"
}, function(err, cat){
if(err){
console.log("error encountered");
} else {
console.log("new cat created")
}
});
Cat.find({}, function(err, cats){
if(err){
console.log("Error encountered");
console.log(err)
} else {
console.log("all cats found")
console.log(cats);
}
})
The output in the terminal appears as follows (multiple entries may be present due to repeated program runs):
node cats.js
Connected to DB!
all cats found
[
{
_id: 5f4ea2d35e48bb06794bb96f,
name: 'George',
age: 11,
temperament: 'Grouchy',
__v: 0
},
...
]
new cat created