保存条目不会将引用添加到我的其他文档中吗?

时间:2019-04-22 19:52:58

标签: javascript mongoose

我有一个ProfileSchema,希望跟踪已发布的帖子。当我保存一个新的帖子时,它具有一个Profile_id,但是当我获取该概况条目时,posts数组为空。如何运作?

配置文件架构

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const ProfileSchema = new mongoose.Schema({
  user: {
    type: Schema.Types.ObjectId,
    ref: 'users'
  },
  handle: {
    type: String,
    required: true,
    max: 40
  },
  posts: [
    {
      type: Schema.Types.ObjectId,
      ref: 'posts'
    }
  ],date:{
    type: Date,
    default: Date.now
  }
})
module.exports = Profile = mongoose.model('profile', ProfileSchema);

发布架构

const PostSchema = new Schema({
  user: {
    type: Schema.Types.ObjectId,
    ref: 'users'
  },
  profile: {
    type: Schema.Types.ObjectId,
    ref: 'profile'
  },
  title: {
    type: String,
    required: true,
    max: 40
  },
  body: {
    type: String,
    required: true
  },
  date: {
    type: Date,
    default: Date.now
  }
})

module.exports = Profile = mongoose.model('posts', PostSchema)

我如何保存

router.post('/', passport.authenticate('jwt', {session: false}), (req,res) => {
  const newPost = new Post({
    title: req.body.title,
    body: req.body.body,
    img: req.body.img,
    user: req.user._id,
    profile: req.body.profile_id
  });
  newPost.save().then(post => res.json(post));
})

我有点困惑,猫鼬文档使用的是我不熟悉或尚未了解其语法的语法。当我获取个人资料数据时,我的user会填充,但是当我填充posts数组时,它会为空。

0 个答案:

没有答案