これは私のpost
モデルである:あなたが見ることができるように私のVirtual Mongooseタイプが表示されないのはなぜですか?
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;
、私は仮想種類のカップルを作成しようとしています:
commentCount
がcomments
の配列の長さを与えます。expired
はここで、コントローラのいずれかのフラグtrue
として、またはfalse
ます:今
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);
},
、ポストマンを使用して、私はポスト自体がうまく作成されていることがわかります。しかし何らかの理由で、私は仮想タイプのために何も戻っていません。
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": []
}
あなたは、私がここで間違ってやっているものを私に教えてくださいことはできますか?私は前に同様のことをしたコースをいくつか沿って続けましたが、コースコードを徹底的に調べています。私はそれを働かせることはできません。
あなたはvirtualsをはJSONオブジェクトにシリアライズ取得したい場合は、ここで説明しhttp://mongoosejs.com/docs/api.html#document_Document-toObjectとしてdoc.toObject({ virtuals: true })
を試してみてください、あなたに
コンソールログでJSON.stringifyを使用していません。それは現れてはいけませんか? – bloppit