如何在select方法中调用mongoose方法
How to call mongoose method in the select method
我有一个代表玩家的猫鼬模型,我希望能够获取玩家并且在选择玩家时,想要像 getter 一样调用 isReady
。
模型看起来像这样:
const PlayerSchema = new Schema({
user: { type: Schema.Types.ObjectId, ref: "User" },
famousPerson: { type: String }
})
PlayerSchema.methods.isReady = function (cb) {
return Boolean(this.famousPerson)
}
我希望能够这样称呼它:
const player = await PlayerModel
.findOne({_id: playerId})
.select(["_id", "username", "isReady"])
我可以将 class 上的方法设置为 getter 吗?
您可以为此使用 mongoose 虚拟,但要按预期工作,您需要配置您的架构,以便它可以 return 虚拟,因为默认情况下不会包括虚拟。
const PlayerSchema = new Schema(
{
famousPerson: { type: String },
},
{
toJSON: { virtuals: true },
toObject: { virtuals: true },
}
);
PlayerSchema.virtual("isReady").get(function () {
return Boolean(this.famousPerson);
});
您可以遵循此代码
const player = await PlayerModel
.findOne({_id: playerId})
.select(" +_id +username +isReady)
我有一个代表玩家的猫鼬模型,我希望能够获取玩家并且在选择玩家时,想要像 getter 一样调用 isReady
。
模型看起来像这样:
const PlayerSchema = new Schema({
user: { type: Schema.Types.ObjectId, ref: "User" },
famousPerson: { type: String }
})
PlayerSchema.methods.isReady = function (cb) {
return Boolean(this.famousPerson)
}
我希望能够这样称呼它:
const player = await PlayerModel
.findOne({_id: playerId})
.select(["_id", "username", "isReady"])
我可以将 class 上的方法设置为 getter 吗?
您可以为此使用 mongoose 虚拟,但要按预期工作,您需要配置您的架构,以便它可以 return 虚拟,因为默认情况下不会包括虚拟。
const PlayerSchema = new Schema(
{
famousPerson: { type: String },
},
{
toJSON: { virtuals: true },
toObject: { virtuals: true },
}
);
PlayerSchema.virtual("isReady").get(function () {
return Boolean(this.famousPerson);
});
您可以遵循此代码
const player = await PlayerModel
.findOne({_id: playerId})
.select(" +_id +username +isReady)