I have code that successfully sends the content in the html post to the mongodb default collection where I store the post and the arrays, I encounter an error (node:23) UnhandledPromiseRejectionWarning: TypeError: Post.findOne(...).toArray is not a function when trying to find the array. I've done research and came to no conclusion and don't know how to fix it, I was hoping to get some sort of feedback and possibly showing improvement code as I'm new to web development.
What I want the script to do is find all the comments in the post and output the result in a console.log or to make it a const so I can reference it within the code, if you need me to elaborate please ask, thanks.
app.js
// mongdb cloud connection is here
mongoose
.connect("secret", {
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true,
useFindAndModify: false,
})
.then(() => {
console.log("connected to mongodb cloud! :)");
})
.catch((err) => {
console.log(err);
});
// middlewares
app.use(express.urlencoded({ extended: true }));
//app.use(express.static("public"));
app.set("view engine", "ejs");
app.use(express.static(__dirname + '/views'));]
app
.get("/post/:id", authenticateUser, async (req, res) => {
const { id } = req.params;
const getPost = await Post.findOne({ _id: id});
const warned = await Post.findOne({ warned: String});
const getusername = await User.findOne({ username: String });
if(id === null) {
res.redirect("/home")
}
//This is where I try to find the post and all the array's to reference when the post is loaded
const getCommentsAll = await Post.findOne().toArray()
console.log("Displaying all comments for " + `post ${id}\n\n` + getCommentsAll);
//Where I reference when the post is loaded
res.render("particularPost", { warned: warned, comments: getCommentsAll, user: req.session.user, post: getPost, postedBy: getusername });
})
Post Mongoose Schema
const mongoose = require("mongoose");
const PostSchema = new mongoose.Schema({
title: {
type: String,
required: true,
},
content: {
type: String,
required: true,
},
postedAt: {
type: String,
default: new Date().toString(),
},
postedBy: {
type: String,
},
warned: {
type: String,
},
comment: [Object]
});
module.exports = new mongoose.model("Post", PostSchema);