【发布时间】:2020-12-17 18:25:19
【问题描述】:
我的代码成功地将 html 帖子中的内容发送到我存储帖子和数组的 mongodb 默认集合,我在尝试查找数组时遇到错误(node:23) UnhandledPromiseRejectionWarning: TypeError: Post.findOne(...).toArray is not a function。我做了研究,没有得出任何结论,也不知道如何解决它,我希望得到一些反馈,并可能显示改进代码,因为我是 web 开发的新手。
我希望脚本做的是找到帖子中的所有 cmets 并将结果输出到 console.log 或将其设为 const 以便我可以在代码中引用它,如果您需要我详细说明,请询问,谢谢。
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 });
})
发布 Mongoose 架构
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);
【问题讨论】:
-
你没有处理承诺拒绝 1 和 2 findOne 方法不能那样工作