为啥 find() 返回未定义?

Posted

技术标签:

【中文标题】为啥 find() 返回未定义?【英文标题】:Why is find() returning undefined?为什么 find() 返回未定义? 【发布时间】:2021-12-11 03:50:39 【问题描述】:

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

我可以显示Account 模型以及更多内容,但我在显示所有帖子时遇到了Post 模型的问题。

即使我在数据库中有帖子,allPosts.js 中的猫鼬函数 Post.find().exec(function(err, posts) 也会不断返回 undefined

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

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


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

我希望能够从我的登录页面进入并显示所有帖子查看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)

【问题讨论】:

【参考方案1】:

下面的修复只需要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;

【讨论】:

以上是关于为啥 find() 返回未定义?的主要内容,如果未能解决你的问题,请参考以下文章

为啥我的 Array.prototype.find() 返回未定义?

即使值存在,为啥对象键返回未定义

为啥这个异步函数返回未定义? [复制]

来自 .ajax() 调用的数据的 jQuery .find() 返回未定义

为啥运行时返回未定义? [复制]

Array Find() 方法在搜索有关 URL 参数的数据时始终返回“未定义”