mongodb 在渲染博客文章条目时,我收到“TypeError:无法读取未定义的属性(阅读“title”),

niwlg2el  于 2023-08-04  发布在  Go
关注(0)|答案(2)|浏览(81)

所以我使用vanilla JS和EJS的博客,我希望每个博客条目完全呈现在一个单独的页面上的基础上“/posts/post._id”,其中

app.get("/posts/:postId", function(req, res){

  const requestedPostId = req.params.postId;

    Post.findOne({_id: requestedPostId}, function(err, post){

      if (!err){
          res.render("post", {
                  title: post.title,
                  content: post.content
                });
      } else {
        console.log(err);
      }

    });

  });

字符串
应该进入我的数据库,并拉出正确的条目,并呈现在我的.ejs页面上。
这是我的代码。

const express = require("express");
const bodyParser = require("body-parser");
const ejs = require("ejs");
const mongoose = require("mongoose");
const _ = require("lodash");
const { stringify } = require("nodemon/lib/utils");

const homeStartingContent = "Lacus vel facilisis volutpat est velit egestas dui id ornare. Semper auctor neque vitae tempus quam. Sit amet cursus sit amet dictum sit amet justo. Viverra tellus in hac habitasse. Imperdiet proin fermentum leo vel orci porta. Donec ultrices tincidunt arcu non sodales neque sodales ut. Mattis molestie a iaculis at erat pellentesque adipiscing. Magnis dis parturient montes nascetur ridiculus mus mauris vitae ultricies. Adipiscing elit ut aliquam purus sit amet luctus venenatis lectus. Ultrices vitae auctor eu augue ut lectus arcu bibendum at. Odio euismod lacinia at quis risus sed vulputate odio ut. Cursus mattis molestie a iaculis at erat pellentesque adipiscing.";
const aboutContent = "Hac habitasse platea dictumst vestibulum rhoncus est pellentesque. Dictumst vestibulum rhoncus est pellentesque elit ullamcorper. Non diam phasellus vestibulum lorem sed. Platea dictumst quisque sagittis purus sit. Egestas sed sed risus pretium quam vulputate dignissim suspendisse. Mauris in aliquam sem fringilla. Semper risus in hendrerit gravida rutrum quisque non tellus orci. Amet massa vitae tortor condimentum lacinia quis vel eros. Enim ut tellus elementum sagittis vitae. Mauris ultrices eros in cursus turpis massa tincidunt dui.";
const contactContent = "Scelerisque eleifend donec pretium vulputate sapien. Rhoncus urna neque viverra justo nec ultrices. Arcu dui vivamus arcu felis bibendum. Consectetur adipiscing elit duis tristique. Risus viverra adipiscing at in tellus integer feugiat. Sapien nec sagittis aliquam malesuada bibendum arcu vitae. Consequat interdum varius sit amet mattis. Iaculis nunc sed augue lacus. Interdum posuere lorem ipsum dolor sit amet consectetur adipiscing elit. Pulvinar elementum integer enim neque. Ultrices gravida dictum fusce ut placerat orci nulla. Mauris in aliquam sem fringilla ut morbi tincidunt. Tortor posuere ac ut consequat semper viverra nam libero.";

const app = express();

app.set('view engine', 'ejs');

app.use(bodyParser.urlencoded({extended: true}));
app.use(express.static("public"));

mongoose.connect("mongodb://localhost:27017/blogDB", {useNewUrlParser: true});  //connect to Mongo DB database

//POST SCHEMA

const postSchema = {
  title: 'string',

  content: 'string'
};

//create mongoose model

const Post = mongoose.model('Post',postSchema);


//global post array

let posts =[];

//home logic

app.get("/", function (req, res) {              //app.get to the homepaghe
 
Post.find({}, function(err, posts){            //Post.find({}) finds all the entries in the post collections

  if(!err) {                                   //if{!err} if there are no errors
  res.render("home", {                         //render the home page
      startingContent:homeStartingContent,    //with the starting content
      posts: posts                            //and all the posts
    });

  }

});

})

// about logic

app.get("/about", function (req, res) {
  res.render("about", {aboutContent:aboutContent});
  
});

//contact logic

app.get("/contact", function (req, res) {
  res.render("contact", {contactContent:contactContent});
  
});

//compose logic

app.get("/compose", function (req, res){
 
  res.render("compose");

});

app.post('/compose', function(req, res) {

const post = new Post ({      //creates  post
  title: req.body.postTitle,  //title 
  content: req.body.postBody  //content
}); 

post.save(function(err){//saves the post to the database
  if(!err) {
    res.redirect("/")  //redirects to the homepage 
  }
});                  

          

});

//Routing Parameters

app.get("/posts/:postId", function(req, res){

  const requestedPostId = req.params.postId;
  
    Post.findOne({_id: requestedPostId}, function(err, post){

      if (!err){
          res.render("post", {
                  title: post.title,
                  content: post.content
                });
      } else {
        console.log(err);
      }

    });
  
  });
 
  app.listen(3000, function() {
    console.log("Server started on port 3000");
  });


所以我犯了两个错误
第一个错误:

Is: node:events:368
      throw er; // Unhandled 'error' event
      ^

TypeError: Cannot read properties of undefined (reading 'title')
    at /home/revolverclyde/Web_Development/ejs-challenge/app.js:112:31
    at /home/revolverclyde/Web_Development/ejs-challenge/node_modules/mongoose/lib/model.js:4981:18
    at processTicksAndRejections (node:internal/process/task_queues:78:11)
Emitted 'error' event on Function instance at:
    at /home/revolverclyde/Web_Development/ejs-challenge/node_modules/mongoose/lib/model.js:4983:15
    at processTicksAndRejections (node:internal/process/task_queues:78:11)
[nodemon] app crashed - waiting for file changes before starting...


第二个是当我添加if语句检查错误时。
错误2:

CastError: Cast to ObjectId failed for value "lodash.js" (type string) at path "_id" for model "Post"
    at model.Query.exec (/home/revolverclyde/Web_Development/ejs-challenge/node_modules/mongoose/lib/query.js:4638:21)
    at model.Query.Query.findOne (/home/revolverclyde/Web_Development/ejs-challenge/node_modules/mongoose/lib/query.js:2516:8)
    at Function.findOne (/home/revolverclyde/Web_Development/ejs-challenge/node_modules/mongoose/lib/model.js:2271:13)
    at /home/revolverclyde/Web_Development/ejs-challenge/app.js:108:10
    at Layer.handle [as handle_request] (/home/revolverclyde/Web_Development/ejs-challenge/node_modules/express/lib/router/layer.js:95:5)
    at next (/home/revolverclyde/Web_Development/ejs-challenge/node_modules/express/lib/router/route.js:137:13)
    at Route.dispatch (/home/revolverclyde/Web_Development/ejs-challenge/node_modules/express/lib/router/route.js:112:3)
    at Layer.handle [as handle_request] (/home/revolverclyde/Web_Development/ejs-challenge/node_modules/express/lib/router/layer.js:95:5)
    at /home/revolverclyde/Web_Development/ejs-challenge/node_modules/express/lib/router/index.js:281:22
    at param (/home/revolverclyde/Web_Development/ejs-challenge/node_modules/express/lib/router/index.js:354:14) {
  messageFormat: undefined,
  stringValue: '"lodash.js"',
  kind: 'ObjectId',
  value: 'lodash.js',
  path: '_id',
  reason: BSONTypeError: Argument passed in must be a string of 12 bytes or a string of 24 hex characters
      at new BSONTypeError (/home/revolverclyde/Web_Development/ejs-challenge/node_modules/bson/lib/error.js:41:28)
      at new ObjectId (/home/revolverclyde/Web_Development/ejs-challenge/node_modules/bson/lib/objectid.js:65:23)
      at castObjectId (/home/revolverclyde/Web_Development/ejs-challenge/node_modules/mongoose/lib/cast/objectid.js:24:12)
      at ObjectId.cast (/home/revolverclyde/Web_Development/ejs-challenge/node_modules/mongoose/lib/schema/objectid.js:247:12)
      at ObjectId.SchemaType.applySetters (/home/revolverclyde/Web_Development/ejs-challenge/node_modules/mongoose/lib/schematype.js:1180:12)
      at ObjectId.SchemaType._castForQuery (/home/revolverclyde/Web_Development/ejs-challenge/node_modules/mongoose/lib/schematype.js:1615:15)
      at ObjectId.SchemaType.castForQuery (/home/revolverclyde/Web_Development/ejs-challenge/node_modules/mongoose/lib/schematype.js:1605:15)
      at ObjectId.SchemaType.castForQueryWrapper (/home/revolverclyde/Web_Development/ejs-challenge/node_modules/mongoose/lib/schematype.js:1582:20)
      at cast (/home/revolverclyde/Web_Development/ejs-challenge/node_modules/mongoose/lib/cast.js:341:32)
      at model.Query.Query.cast (/home/revolverclyde/Web_Development/ejs-challenge/node_modules/mongoose/lib/query.js:5073:12),
  valueType: 'string'


你知道我做错了什么吗?

  • 谢谢-谢谢
e0bqpujr

e0bqpujr1#

所以我想明白了。
lodash由中的_id激活
“Post.findOne({_id:requestedPostId},function(err,post){...”
我把它取下来了所以现在写着
“Post.findOne({id:requestedPostId},function(err,post){...”
现在一切都运行得很完美。

p4rjhz4m

p4rjhz4m2#

你可以试着签入你的ejs文件。如果你有这个:<script src="lodash.js"> </script>只要删除它。希望能帮到你。。

相关问题