首页 > 解决方案 > 使用来自 NestJs 中另一个模型的 find() 方法的数据创建虚拟字段

问题描述

我正面临以下问题。

我正在一个模式中工作,在一个集合中创建这个虚拟字段,但是要填充这个字段,我需要从另一个集合中获取数据。

我需要以某种方式注入 nestJs mongoose 库,然后使用 .find({}) 方法。

我面临的问题是我无法在模式中加载模型并且“猫鼬”库无法正常工作。

代码如下。

    export const SongSchema = new Schema({
  _id: { type: String },
    title:{type:String,required:true},
    singer: { type: String, required: true },
    imageURL: { type: String},
    asset: { type: Schema.Types.ObjectId, ref: 'Asset' },
    list: { type: Schema.Types.ObjectId, ref: 'List' },
    createdAt:{
        type:Date,
        default:Date.now
    },
  deleted: { type: Boolean },
  status: { type: Boolean }
},
{toJSON:{
  virtuals:true}
})

var Point = mongoose.model('Points', PointSchema)
async function getTotals  (id) {
 var points = await Point.find({company:id}).catch((err)=>{console.log(err);
 })
  return points
  
} 

SongSchema.virtual('totalPoint').get(function () {
  var total = getTotals(this.id)
 })

非常感谢

标签: mongoosemodelschemanestjsvirtual

解决方案


推荐阅读