2017-02-05 9 views
0

これは私の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; 

、私は仮想種類のカップルを作成しようとしています:

  1. commentCountcommentsの配列の長さを与えます。
  2. 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 })を試してみてください、あなたに

+0

コンソールログでJSON.stringifyを使用していません。それは現れてはいけませんか? – bloppit

答えて

1

ありがとうございます。

+0

あなたの答えをありがとう。これはどこで使うのですか?それはなぜ必要なのですか? – bloppit

+0

これを追加しました。ありがとうございます。 私は前にマングースでプロジェクトをしていましたが、これは必要ではありませんでした。これはなぜでしょうか? – bloppit

+1

@bloppit仮想オブジェクトは新しいものを格納しないので、デフォルトの動作で仮想プロパティを必ずしもシリアル化する必要はありません。 – Legendecas

関連する問題