问题
Here is my code in model.js file:
const mongoose = require("mongoose");
const con = require("./connection");
con();
const schoolNotices = mongoose.model("schoolNotices",
{
title:{
type: String
},
date:{
type:String
},
details:{
type:String
}
});
module.exports = schoolNotices;
And I have imported this code into students.js file
router.route("/notices")
.get((req,res)=>{
schoolNotices.find({},(err,docs)=>{
if(err){
return console.log(err)
}
res.render("studentNotices",{title:"Notices",data:docs})
})
}).post(urlencodedParser,(req,res)=>{
});
schoolNotices collection has 3 objects like:
{
"_id" : ObjectId("5ffa80077245b1208057a4ca"),
"title" : "annual sports day",
"date" : "03-01-2021",
"details" : "The point of using Lorem Ipsum is that it has a more-or-less normal distribution of
letters, as opposed to using 'Content here, content here', making it look like readable English.
Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model
text"
}
find({},(err,docs))
should return an array of all objects in docs
but it returns an empty array.
回答1:
You are missing schema creation part, using mongoose.Schema
,
const schoolNotices = mongoose.model("schoolNotices",
new mongoose.Schema(
{
title:{
type: String
},
date:{
type:String
},
details:{
type:String
}
},
{ collection: "schoolNotices" } // optional
)
);
来源:https://stackoverflow.com/questions/65672567/find-returns-an-empty-array-mongoose