简体   繁体   中英

How to call mongoose method in the select method

I have a mongoose model that represents a player and want to be able to fetch the player and when selecting the player, want to call isReady like a getter.

The model looks like so:

const PlayerSchema = new Schema({
  user: { type: Schema.Types.ObjectId, ref: "User" },
  famousPerson: { type: String }
})

PlayerSchema.methods.isReady = function (cb) {
  return Boolean(this.famousPerson)
}

And I want to be able to call it like so:

const player = await PlayerModel
      .findOne({_id: playerId})
      .select(["_id", "username", "isReady"])

Am I able to set the method on the class as a getter?

You can use mongoose virtuals for this, but to work as expected you need to configure your schema so that it can return virtuals, because by default virtuals will not be included.

const PlayerSchema = new Schema(
  {
    famousPerson: { type: String },
  },
  {
    toJSON: { virtuals: true },
    toObject: { virtuals: true },
  }
);

PlayerSchema.virtual("isReady").get(function () {
  return Boolean(this.famousPerson);
});

You Can Follow This Code

const player = await PlayerModel
      .findOne({_id: playerId})
      .select(" +_id +username +isReady)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM