猫鼬是否在选择中支持虚拟字段(例如SQL)

猫鼬是否在选择中支持虚拟字段(例如SQL)

问题描述:

在SQL中,我可以使用状态"虚拟字段进行以下SELECT语句:

In SQL I can make the following SELECT statement with the 'status' virtual field:

SELECT 
   CASE 
      WHEN field = 1 THEN 'sale'
      ELSE 'none'
   END as status

猫鼬里有类似的东西吗?

Does something like is in mongoose?

是.猫鼬模式支持虚拟.请参阅指南的架构部分.我想您可能想要这样的东西:

Yes. Mongoose schemas support virtuals. Have a look at the schema section of the guide. I think you may want something like this:

var salesSchema = new Schema({
  sale: Number
});

salesSchema.virtual('status').get(function() {
  if (this.sale === 1) {
    return 'sale';
  } else {
    return 'none';
  }
});