为什么 find({}) 返回未定义?

Why is find({}) returning undefined?

你好,我正在制作一个基本的社交应用程序,目前有一个 Account 和一个 Post 模型。

我能够显示 Account 模型以及更多模型,但是我在显示所有 post 模型时遇到了 Post 模型的问题。

allPosts.js 中的 mongoose 函数 Post.find({}).exec(function(err, posts) 一直返回 undefined 即使我在数据库中有 posts。

注意:我可以成功 post 到 posts 集合,只是无法读取它们。

我可以显示所有帐户,但不能显示所有 posts。


更新:我现在可以创建一个 post,然后被重定向回 allPosts.pug 页面,并查看除刚刚创建的 post 之外的所有 post ,看看 addNewPost.js.

我希望能够从我的登录页面转到显示的所有 post 查看 index.js

/* Account.js */

const mongoose = require("mongoose")

const Account = mongoose.model("Account", {
    name: String,
    lastName: String,
    email: {type: String, unique: true, lowercase: true, required: true},
    phoneNumber: String,
    password: String
})

module.exports = Account
/* Post.js */

const mongoose = require("mongoose")

const Post = mongoose.model("Post", {
    emailId: {type: String, required: true},
    postTitle: {type: String, required: true},
    postMessage: {type: String, required: true},
    datePosted: {type: Date, default: Date.now},
})

module.exports = Post
/* allPosts.js */

var express = require('express');
var router = express.Router();
const Account = require("../models/account")
const Post = require("../models/post")

/* GET all posts page. */
router.get('/', function(req, res, next) {
    Post.find({}).exec(function(err, posts) {
        res.render("allPosts", {title: "Social Application", posts: posts})
    })
})

module.exports = router;
/* allPosts.pug */

extends layout 

block content 
    h1 #{title}

    if posts === undefined
        h1 No posts to show here 
    else 
        each post in posts
            div(class="container")
                div(class="jumbotron")
                    h1= post.postTitle 
                    h1= post.postMessage
    br
    
    a(href="/addNewPost"): button(class="btn btn-primary float-end") Add post
    a(href="/logout"): button(class="btn btn-primary float-end") Logout
/* addNewPost.js */

var express = require('express');
const Post = require('../models/post');
var router = express.Router();

/* GET all posts page. */
router.get('/', function(req, res, next) {
    res.render("addNewPost", {title: "Social Application"})
});

router.post('/', function(req, res, next) {
    var emailId = req.session.email
    var postTitle = req.body.postTitle
    var postMessage = req.body.postMessage

    var postData = {
        emailId: emailId,
        postTitle: postTitle,
        postMessage: postMessage
    }

    var aPost = new Post(postData)
    aPost.save(function(err) {
        if (err) {
            console.log(err)
        } else {
            console.log("Post saved successfully !")
        }
    })

    Post.find({}).exec(function(err, posts) {
        res.render("allPosts", {title: "All posts", posts: posts})
    })
})

module.exports = router;
/* index.js */

var express = require('express');
var router = express.Router();
const Account = require("../models/account")
const bcrypt = require("bcrypt");

/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { title: "Social Application" });
});

/* POST home page */
router.post('/', function(req, res, next) {
  var email = req.body.email
  var password = req.body.password

  Account.findOne({email:email}).exec(function(err, account) {
    if (account) {
      if (bcrypt.compareSync(password, account.password)) {
        req.session.email = account.email
        req.session.userLoggedIn = true
        res.render("allPosts", {title: "All Posts"})
      } else {
        res.render("index", {error: "Your credentials are incorrect !", title: "Social Application"})
      }
    } else {
      res.render("index", {error: "This account does not exist !", title: "Social Application"})
    }
  })
})

module.exports = router;
/* Trace */

TypeError: C:\Users\bmxfi\Desktop\code\NodeJavascript\SocialApplication\SocialApplication\views\allPosts.pug:7
    5| 
    6|     
  > 7|     each post in posts
    8|         div(class="container")
    9|             div(class="jumbotron")
    10|                 h1= post.postTitle 

Cannot read property 'length' of undefined
    at eval (eval at wrap (C:\Users\bmxfi\node_modules\pug\node_modules\pug-runtime\wrap.js:6:10), <anonymous>:36:32)
    at eval (eval at wrap (C:\Users\bmxfi\node_modules\pug\node_modules\pug-runtime\wrap.js:6:10), <anonymous>:71:4)
    at template (eval at wrap (C:\Users\bmxfi\node_modules\pug\node_modules\pug-runtime\wrap.js:6:10), <anonymous>:93:7)
    at Object.exports.renderFile (C:\Users\bmxfi\node_modules\pug\lib\index.js:454:38)
    at Object.exports.renderFile (C:\Users\bmxfi\node_modules\pug\lib\index.js:444:21)
    at View.exports.__express [as engine] (C:\Users\bmxfi\node_modules\pug\lib\index.js:493:11)
    at View.render (C:\Users\bmxfi\node_modules\express\lib\view.js:135:8)
    at tryRender (C:\Users\bmxfi\node_modules\express\lib\application.js:640:10)
    at Function.render (C:\Users\bmxfi\node_modules\express\lib\application.js:592:3)
    at ServerResponse.render (C:\Users\bmxfi\node_modules\express\lib\response.js:1012:7)

下面的修复只是必须 redirect("allPosts") 到视图而不是 res.render("allPosts", {title: "Social Application")

/* index.js */

var express = require('express');
var router = express.Router();
const Account = require("../models/account")
const bcrypt = require("bcrypt");

/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { title: "Social Application" });
});

/* POST home page */
router.post('/', function(req, res, next) {
  var email = req.body.email
  var password = req.body.password

  Account.findOne({email:email}).exec(function(err, account) {
    if (account) {
      if (bcrypt.compareSync(password, account.password)) {
        req.session.email = account.email
        req.session.userLoggedIn = true
        res.redirect("allPosts")
      } else {
        res.render("index", {error: "Your credentials are incorrect !", title: "Social Application"})
      }
    } else {
      res.render("index", {error: "This account does not exist !", title: "Social Application"})
    }
  })
})

module.exports = router;
/* addNewPost.js */

var express = require('express');
const Post = require('../models/post');
var router = express.Router();

/* GET all posts page. */
router.get('/', function(req, res, next) {
    res.render("addNewPost", {title: "Social Application"})
});

router.post('/', function(req, res, next) {
    var emailId = req.session.email
    var postTitle = req.body.postTitle
    var postMessage = req.body.postMessage

    var postData = {
        emailId: emailId,
        postTitle: postTitle,
        postMessage: postMessage
    }

    var aPost = new Post(postData)
    aPost.save(function(err) {
        if (err) {
            console.log(err)
        } else {
            console.log("Post saved successfully !")
        }
    })

    res.redirect("allPosts")
})

module.exports = router;