【问题标题】:find({}) returns an empty array mongoosefind({}) 返回一个空数组 mongoose
【发布时间】:2021-01-12 20:18:08
【问题描述】:

这是我在 model.js 文件中的代码:

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;

我已经将此代码导入到students.js文件中

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 集合有 3 个对象,例如:

{
    "_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)) 应该返回一个包含docs 中所有对象的数组,但它返回一个空数组。

【问题讨论】:

    标签: node.js mongodb mongoose find


    【解决方案1】:

    您缺少架构创建部分,使用mongoose.Schema

    const schoolNotices = mongoose.model("schoolNotices",
        new mongoose.Schema(
            {
                title:{
                    type: String
                },
                date:{
                    type:String
                },
                details:{
                    type:String
                }
            },
            { collection: "schoolNotices" } // optional
        )
    );
    

    【讨论】:

    • 您需要检查与正确服务器的数据库连接并确认集合名称。
    • 好的我尝试使用这个模型保存一些数据,它将数据保存在一个新的集合名称“schoolnotices”中,我使用的是 mongoose 版本 5.11.11,它不允许我使用 camelCase集合名称
    • 如果您按照我的回答指定了集合名称,它应该可以工作,请查看 mongoose docsrelated question
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-04-27
    • 2021-09-16
    • 1970-01-01
    • 1970-01-01
    • 2019-10-27
    • 2022-01-21
    • 2017-11-13
    相关资源
    最近更新 更多