猫鼬与NestJS-一对多

时间:2018-09-07 22:27:20

标签: node.js typescript mongoose nestjs

我有一个问题,我无法使用Mongoose获得2个架构之间的关系,我是一个新用户,正在使用NestJS,这是一个使用TypeScript的NodeJS框架。

我有以下文件:

user.schema.ts

import * as mongoose from 'mongoose';

export const UserSchema = new mongoose.Schema({
    name: String,
    email: String,
    role: Number,
    tokens: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Token'}]
});

token.schema.ts

import * as mongoose from 'mongoose';

export const TokenSchema = new mongoose.Schema({
    token: String,
    refreshToken: String,
    createdAt: String,
    expiresAt: String,
    isValid: Boolean,
    userId: [{ type: mongoose.Schema.Types.ObjectId, ref: 'User'}]
});

因此,可以看到该关系,但是我不知道如何获取User模式的子级。 在我的话里,我有这个:

await this.userModel.find().populate('user', 'tokens').exec()

据我所知,这是获得2个架构之间的关系。 顺便说一句:集合是用户和令牌。

如果您有任何反馈意见或需要澄清的地方,我将不胜感激。

2 个答案:

答案 0 :(得分:2)

我已经通过一对多关系解决了我的问题:

package.json:

"@nestjs/mongoose": "7.0.2"
"mongoose": "^5.10.14"

作为示例,我将使用本期的架构(UserToken):

  1. 创建Token架构
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { Document, Types } from 'mongoose';

@Schema({_id: false})
export class Token {

  @Prop({type: Types.ObjectId})
  _id: Types.ObjectId;

  @Prop()
  token: string;

  @Prop()
  refreshToken: string;

  @Prop()
  createdAt: Date; // You can use Date here.

  @Prop()
  expiresAt: Date;

  @Prop()
  isValid: boolean;
}

export const TokenSchema = SchemaFactory.createForClass(Token);
  1. Token模式添加到TokenModule
import { MongooseModule } from '@nestjs/mongoose';

@Module({
  imports: [
    MongooseModule.forFeature([
      { name: Token.name, schema: TokenSchema },
    ]),
  ],
  // ...
})
export class TokenModule {}
  1. 创建User架构
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { Document, Types } from 'mongoose';

export type UserDocument = User & Document;

@Schema({_id: false})
export class User {

  @Prop({type: Types.ObjectId})
  _id: Types.ObjectId;

  @Prop()
  name: string;

  @Prop()
  email: string;

  @Prop()
  role: number;

  @Prop(type: [Types.ObjectId], ref: Token.name)
  tokens: Token[];
}

export const UserSchema = SchemaFactory.createForClass(User);
  1. User模式添加到UserModule
import { MongooseModule } from '@nestjs/mongoose';

@Module({
  imports: [
    MongooseModule.forFeature([
      { name: User.name, schema: UserSchema },
    ]),
  ],
  // ...
})
export class UserModule {}
  1. populate中使用UserService函数

@Injectable()
export class UserService {

  constructor(
    @InjectModel(User.name) private userModel: Model<UserDocument>,
  ) {}

  async getUserWithPopulate(id: string) {
    // Here is the ace in the hole, you need to specify the path (tokens) and the model (Token.name).
    await this.userModel
      .find()
      .populate('tokens', null, Token.name)
      .exec()

  }
}

答案 1 :(得分:0)

问题是我没有正确存储密钥。