我有一个非常简单的“社交网络”应用程序:用户可以注册,写帖子(喜欢/不喜欢它们)以及评论帖子。
我的发帖模式有问题:
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
// Create Schema
const PostSchema = new Schema({
user: {
type: Schema.Types.ObjectId,
ref: "user",
},
text: {
type: String,
required: true,
},
name: {
type: String,
},
avatar: {
type: String,
},
likes: [
{
user: {
type: Schema.Types.ObjectId,
ref: "user",
},
},
],
comments: [
{
user: {
type: Schema.Types.ObjectId,
ref: "user",
},
},
{
text: {
type: String,
required: true,
},
},
{
name: {
type: String,
},
},
{
avatar: {
type: String,
},
},
{
date: {
type: Date,
default: Date.now,
},
},
],
date: {
type: Date,
default: Date.now,
},
});
module.exports = Profile = mongoose.model("post", PostSchema);
当我收到我的POST请求发表评论时...
// @route POST api/posts/comment/:id
// @desc Add comment to post
// @access Private
router.post(
"/comment/:id",
passport.authenticate("jwt", { session: false }),
(req, res) => {
const { errors, isValid } = validatePostInput(req.body);
// Check Validation
if (!isValid) {
// If any errors, send 400 with errors object
return res.status(400).json(errors);
}
Post.findById(req.params.id)
.then(post => {
const newComment = {
text: req.body.text,
name: req.body.name,
avatar: req.body.avatar,
user: req.user.id,
};
console.log("newComment: ", newComment);
// Add to comments array
post.comments.unshift(newComment);
console.log("post: ", post.comments);
// Save
post.save().then(post => res.json(post));
})
.catch(err => res.status(404).json({ postnotfound: "No post found" }));
},
);
保存在post.comments数组中的唯一字段是User。不是其他字段(文本,名称,头像,日期)。
我的console.log("newComment: ", newComment);
正确地返回了具有其所有属性的完整对象,但是在下面的两行中,console.log("post: ", post.comments);
仅返回了注释_id和用户,而这些是数据库中唯一保存的字段。
我在这里想念什么?
答案 0 :(得分:1)
在创建模式结构时存在一些问题,这是正确的方法:
comments: [
{
user: {
type: Schema.Types.ObjectId,
ref: "user",
},
text: {
type: String,
required: true,
},
name: {
type: String,
},
avatar: {
type: String,
},
date: {
type: Date,
default: Date.now,
},
}
]
有效结构不过是这样(显示上面所做的更改):
comments: [{
user: {},
text: {},
// others...
}]