Javascript 为什么不';我的虚拟猫鼬不会出现吗?
这是我的Javascript 为什么不';我的虚拟猫鼬不会出现吗?,javascript,node.js,mongodb,express,mongoose,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: {
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;
现在,使用Postman,我可以看到帖子本身创建得很好。但是出于某种原因,我没有得到虚拟类型的任何信息,无论是commentCount
还是expired
这就是我得到的回应:
}
"__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": []
}
你能告诉我我做错了什么吗?我已经学习了好几门课程,在这些课程中我以前也做过类似的练习,我正在仔细阅读课程代码。不过我没办法解决
谢谢如果您想将虚拟对象序列化为json对象,请尝试
doc.toObject({virtuals:true})
,如本文所述。谢谢您的回答。我在哪里用这个?为什么有必要?好的,我加了这个,谢谢。我以前做过一个关于猫鼬的项目,这是没有必要的。为什么会这样?@bloppit我想因为virtuals不存储任何新东西,所以不一定要以默认行为序列化虚拟属性。@bloppit在处理结束时使用它,因为doc.toObject
的结果不是mongoose文档类型,您无法与数据库进行任何进一步的交互。我在控制台日志中没有使用JSON.stringify。它不应该出现吗?
}
"__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": []
}