find({}) returns an empty array mongoose

依然范特西╮ 提交于 2021-02-11 06:56:10

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!