MongooseJS:很难填充评论列表



我有一个名为Post的模式,在该模式中有一个comments属性。

const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const PostSchema = new Schema({
user: {
type: Schema.Types.ObjectId,
ref: "users",
},
text: {
type: String,
required: true,
},
name: {
type: String,
},
avatar: {
type: String,
},
likes: [
{
user: {
type: Schema.Types.ObjectId,
ref: "users",
},
},
],
comments: [
{
type: Schema.Types.ObjectId,
ref: "comments",
},
],
date: {
type: Date,
default: Date.now,
},
});
module.exports = Post = mongoose.model("post", PostSchema);

这是我的评论模式。

const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const CommentSchema = new Schema({
post: {
type: Schema.Types.ObjectId,
ref: "posts",
},
user: {
type: Schema.Types.ObjectId,
ref: "users",
},
text: {
type: String,
required: true,
},
name: {
type: String,
},
avatar: {
type: String,
},
likes: [
{
user: {
type: Schema.Types.ObjectId,
ref: "users",
},
},
],
replies: [
{
type: Schema.Types.ObjectId,
ref: "comments",
},
],
date: {
type: Date,
default: Date.now,
},
});
module.exports = Comment = mongoose.model("comment", CommentSchema);

当我打印出帖子访问的数据时,我会得到如下结果:

{
"_id": "630a82d564540e7196fe4887",
"user": "6301a168783647db9f7a37c8",
"text": "For the police I say ____ you punk, reading my rights and ____ it's all junk",
"name": "e",
"avatar": "//www.gravatar.com/avatar/8fd046f9f8f50ab2903fa9fd6c845134?s=200&r=pg&d=mm",
"comments": [
"630aa7c425ae8add2b275b53",
"630a834959110e8e3305b471",
"630a83200cd98eb07fb5f543"
],
"likes": [],
"date": "2022-08-27T20:47:17.888Z",
"__v": 3
}

我已经尝试填充下面显示的评论,但我得到了一个错误:

router.post(
"/commentOnPost/",
[auth, check("text", "Text is required").not().isEmpty()],
async (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
try {
const user = await User.findById(req.user.id);
const post = await Post.findById(req.body.post_id).populate('comments');
let newComment = Comment({
post: post.id,
text: req.body.text,
name: user.name,
avatar: user.avatar,
user: req.user.id,
});
await newComment.save();
post.comments.unshift(newComment);
await post.save();
return res.json(await post);
} catch (err) {
errorLog(err);
res.status(500).send("Server error");
}
}
);
Sat Aug 27 2022 19:27:22 GMT-0400 (Eastern Daylight Time),  -> MissingSchemaError: Schema hasn't been registered for model "comments".
Use mongoose.model(name, schema)

Comment模式中,您将模型命名为">评论";。但在Post模式中,您将其引用为">评论";。

更改Post模式中的代码如下:

comments: [{ type: Schema.Types.ObjectId, ref: "comment" }],

最新更新