LoginSignup
4
5

More than 5 years have passed since last update.

Mongooseでvirtualが出力できないときの対処法

Last updated at Posted at 2016-05-26

Mongooseにはvirtualという機能がある。

例えば、データベースにはfirstNameとlastNameという項目があるが、実際にfindするときはfullNameも吐き出して欲しいとする。

そんな時に、以下の様な感じでスキーマを定義したあとにvirtualを使うとfirstNameとlastNameをくっつけたfullNameを吐き出したりすることができる。

これで実際にデータベース上ではfullNameを持たないけど、findしたときだけ仮想的にfullNameを生成して吐き出してくれる。

schema.virtual('fullName').get(function() {
  return this.firstName + this.lastName;
});

はずなのだが、さっきやってみると吐き出されなくて焦った。
前まではこれでうまくいっていたのでかなり焦った。

解決方法

以下を記述したら、ちゃんと出力されるようになりました。

schema.set("toJSON", { virtuals: true });
4
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
5