首先在schema定义一下你的目标collection

import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import * as mongoose from 'mongoose';
import { Meta } from './meta.schema' //引入目标的schema


@Schema()
export class Article {
  @Prop({
    type: mongoose.Schema.Types.ObjectId, //根据ObjectId关联
    ref: 'Meta' 
  })
  category_id: Meta;  //输入你要关联上的集合的scema

}

export const ArticleSchema = SchemaFactory.createForClass(Article);

查询的时候使用

this.ArticleModel.findOneAndUpdate({ _id: id, hidden: 0 }, { $inc: { views: 1 } }, { useFindAndModify: false }).populate('category_id')

如果是一对多查询的时候

定义的时候用一个数组把数据包进去就可了

 @Prop([{
    type: mongoose.Schema.Types.ObjectId, //根据ObjectId关联
    ref: 'Meta' 
  }])
Last modification:January 5th, 2021 at 09:16 pm
If you think my article is useful to you, please feel free to appreciate