为什么我的虚拟猫鼬类型不会出现?

时间:2017-02-05 15:21:14

标签: javascript node.js mongodb express mongoose

这是我的post型号:

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

const PostSchema = new Schema({
  text: String,
  image: String,
  author: {
    type: Schema.Types.ObjectId,
    ref: 'user',
    required: true
  },
  university: {
    type: String,
    required: true
  },
  uniOnly: {
    type: Boolean,
    required: true
  },
  createdAt: {
    type: Number,
    required: true
  },
  expiresAt: {
    type: Number,
    required: true
  },
  voteCount: {
    type: Number,
    required: true
  },
  comments: [{
    type: Schema.Types.ObjectId,
    ref: 'comment'
  }],
  commenters: [{
    type: Schema.Types.ObjectId,
    ref: 'user'
  }],
  categories: [{
    type: String
  }]
});

PostSchema.virtual('commentCount').get(function () {
  return this.comments.length;
});

PostSchema.virtual('expired').get(function () {
  const now = new Date().getTime();

  return now <= this.expiresAt;
});

const Post = mongoose.model('post', PostSchema);

module.exports = Post;

如您所见,我试图创建几种虚拟类型:

  1. commentCount将给出comments
  2. 数组的长度
  3. expired会标记为truefalse
  4. 这是控制器:

    create(req, res, next) {
        const postProps = req.body;
        const now = new Date().getTime();
        const expiresAt = now + 43200000;
    
        const { author, text, image, categories, university, uniOnly } = postProps;
    
        Post.create({
          author,
          text,
          image,
          categories,
          university,
          uniOnly,
          createdAt: now,
          voteCount: 0,
          expiresAt,
        })
          .then(post => res.send(post))
          .catch(next);
      },
    

    现在,使用Postman我可以看到帖子本身正在创建中。但出于某种原因,我还没有找到虚拟类型的任何内容,commentCountexpired

    这是我回复的内容:

    }
      "__v": 0,
      "author": "5896623ff821b14c4470cf97",
      "text": "this is ANOTHER post",
      "university": "University of Birmingham",
      "uniOnly": false,
      "createdAt": 1486306414679,
      "voteCount": 0,
      "expiresAt": 1486349614679,
      "_id": "58973c6ef24ca4828c2adae1",
      "categories": [
        "music",
        "dance"
      ],
      "commenters": [],
      "comments": []
    }
    
    你能告诉我我在这里做错了什么吗?我之前跟着几个我已经完成类似的课程,然后我在课程代码中搜索。我不能解决这个问题。

    谢谢

1 个答案:

答案 0 :(得分:1)

如果要将虚拟序列化为json对象,请尝试doc.toObject({ virtuals: true }),如http://mongoosejs.com/docs/api.html#document_Document-toObject所示。