【发布时间】:2019-02-14 06:01:33
【问题描述】:
我有一个非常简单的“社交网络”应用:用户可以注册、写帖子、喜欢/不喜欢他们以及评论帖子。
我的帖子架构有问题:
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);
当我收到我对 cmets 的 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.cmets 数组中的唯一字段是用户。不是其他字段(文本、姓名、头像、日期)。
我的console.log("newComment: ", newComment); 正确地返回了完整的对象及其所有属性,但是,在下面的 2 行中,console.log("post: ", post.comments); 只返回注释 _id 和用户,这些是保存在数据库中的唯一字段...
我在这里错过了什么?
【问题讨论】: