我有一個名為 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)
uj5u.com熱心網友回復:
在您的Comment架構中,您將模型命名為“ comment ”。但在Post架構中,您將其稱為“評論”。
像這樣更改Post架構中的代碼:
comments: [{ type: Schema.Types.ObjectId, ref: "comment" }],
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/504022.html
標籤:javascript 节点.js mongodb 表示 猫鼬
上一篇:貓鼬,更新的嵌套陣列
