1

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.

turivishal
  • 34,368
  • 7
  • 36
  • 59
Shofiul
  • 50
  • 1
  • 8

1 Answers1

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
    )
);
turivishal
  • 34,368
  • 7
  • 36
  • 59
  • you need to check database connection with right server and confirm collection name. – turivishal Jan 11 '21 at 18:43
  • ok I try to save some data using this model, it saves data in a new collection name "schoolnotices", I am using mongoose version 5.11.11, it doesn't allow me to use camelCase in collection name – Shofiul Jan 12 '21 at 09:55
  • It should work if you have specified collection name as per my answer look at [mongoose docs](https://mongoosejs.com/docs/guide.html#collection) and [related question](https://stackoverflow.com/questions/7486528/mongoose-force-collection-name) – turivishal Jan 12 '21 at 10:36