Mongoose不保存我的POST请求的所有字段

问题描述 投票:0回答:1

我有一个非常简单的“社交网络”应用程序:用户可以注册,撰写帖子,喜欢/不同于他们并评论帖子。

我的帖子架构有问题:

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);正确返回包含其所有属性的完整对象,但接下来,2行,console.log("post: ", post.comments);只返回注释_id和用户,这些是DB中保存的唯一字段...

我在这里想念的是什么?

node.js mongodb mongoose
1个回答
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...
}]
© www.soinside.com 2019 - 2024. All rights reserved.