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);
This is because toArray
does not exists for the method findOne
as findOne returns only one object. So the correct implementation would be
await Post.findOne({... })
toArray
can only be chained after a method that returns multiple documents, like the find
method.
await Post.find({... }).toArray()
EDIT
My bad. I missed the fact that you are using mongoose. .toArray()
is only needed when you use the MongoDB native driver. Mongoose takes care of this for you. You should be able to write just Post.find({... })
and mongoose will return an array for you.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.