如何在 nestjs 中填充 mongoose 引用?
How to populate mongoose references in nestjs?
我定义了人物和故事模式:
@Schema()
export class Person extends Document {
@Prop()
name: string;
}
export const PersonSchema = SchemaFactory.createForClass(Person);
@Schema()
export class Story extends Document {
@Prop()
title: string;
@Prop()
author: { type: MongooseSchema.Types.ObjectId , ref: 'Person' }
}
export const StorySchema = SchemaFactory.createForClass(Story);
在我的服务中,我实现了保存和读取功能:
async saveStory(){
const newPerson = new this.personModel();
newPerson.name = 'Ian Fleming';
await newPerson.save();
const newStory = new this.storyModel();
newStory.title = 'Casino Royale';
newStory.author = newPerson._id;
await newStory.save();
}
async readStory(){
const stories = await this.storyModel.
findOne({ title: 'Casino Royale' })
console.log('stories ',stories);
}
当我 运行 readStory() 时,我得到以下输出:
stories {
_id: 5f135150e46fa5256a3a1339,
title: 'Casino Royale',
author: 5f135150e46fa5256a3a1338,
__v: 0
}
当我将 populate('author')
添加到我的查询时,我得到的作者为 null:
stories {
_id: 5f135150e46fa5256a3a1339,
title: 'Casino Royale',
author: null,
__v: 0
}
如何使用引用的个人文档填充作者字段?
找到了。
我的错误在于定义架构。
应该是:
@Schema()
export class Story extends Document {
@Prop()
title: string;
@Prop({ type: MongooseSchema.Types.ObjectId , ref: 'Person' })
author: MongooseSchema.Types.ObjectId
}
经过大量阅读和测试 nestjs 中的 mongoose 引用。我认为可以改进接受的答案。我将分两步展示这一点。第一步是显示 MongooseSchema 的声明,并包括 @illnr 关于作者 属性 使用 Types.ObjectId
而不是 MongooseSchema.Types.ObjectId
.
的评论
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { Document, Types, Schema as MongooseSchema } from 'mongoose';
@Schema()
export class Story extends Document {
@Prop()
title: string;
@Prop({ type: MongooseSchema.Types.ObjectId , ref: 'Person' })
author: Types.ObjectId
}
export const StorySchema = SchemaFactory.createForClass(Story);
作为第二步,我认为使用 Person class 作为作者 属性 的类型可以提高可读性,如此处所示。
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { Document, Types, Schema as MongooseSchema } from 'mongoose';
import { Person } from './person.schema'
@Schema()
export class Story extends Document {
@Prop()
title: string;
@Prop({ type: MongooseSchema.Types.ObjectId , ref: 'Person' })
author: Person
}
export const StorySchema = SchemaFactory.createForClass(Story);
None 以上对我有用,我不得不使用 populate()
。参考资料来自 https://dev.to/mossnana/nestjs-with-mongoose-populate-4mo7?signin=true
完整代码和结构示例
users.service.ts
import { User, UserDocument } from 'src/schemas/user.schema';
import { Role, RoleDocument } from 'src/schemas/role.schema';
...
constructor(
@InjectModel(User.name) private userModel: Model<UserDocument>,
@InjectModel(Role.name) private roleModel: Model<RoleDocument>,
private roleService: RolesService
) {}
async findOne(id: string) {
return await this.userModel.findOne({ _id: id }).populate('role', '', this.roleModel).exec();
}
user.schema.ts
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import * as mongoose from 'mongoose';
import { Role } from './role.schema';
export type UserDocument = User & mongoose.Document;
@Schema()
export class User {
@Prop({ required: true, type: String })
email: string;
@Prop({ type: String })
name: string;
@Prop({ type: mongoose.Schema.Types.ObjectId, ref: 'Role' })
role: Role;
}
export const UserSchema = SchemaFactory.createForClass(User);
role.schema.ts
export type RoleDocument = Role & mongoose.Document;
@Schema()
export class Role {
@Prop({ type: String, required: true, unique: true, index: true })
name: string;
@Prop({ type: [String], required: true })
permissions: string[];
}
export const RoleSchema = SchemaFactory.createForClass(Role);
我定义了人物和故事模式:
@Schema()
export class Person extends Document {
@Prop()
name: string;
}
export const PersonSchema = SchemaFactory.createForClass(Person);
@Schema()
export class Story extends Document {
@Prop()
title: string;
@Prop()
author: { type: MongooseSchema.Types.ObjectId , ref: 'Person' }
}
export const StorySchema = SchemaFactory.createForClass(Story);
在我的服务中,我实现了保存和读取功能:
async saveStory(){
const newPerson = new this.personModel();
newPerson.name = 'Ian Fleming';
await newPerson.save();
const newStory = new this.storyModel();
newStory.title = 'Casino Royale';
newStory.author = newPerson._id;
await newStory.save();
}
async readStory(){
const stories = await this.storyModel.
findOne({ title: 'Casino Royale' })
console.log('stories ',stories);
}
当我 运行 readStory() 时,我得到以下输出:
stories {
_id: 5f135150e46fa5256a3a1339,
title: 'Casino Royale',
author: 5f135150e46fa5256a3a1338,
__v: 0
}
当我将 populate('author')
添加到我的查询时,我得到的作者为 null:
stories {
_id: 5f135150e46fa5256a3a1339,
title: 'Casino Royale',
author: null,
__v: 0
}
如何使用引用的个人文档填充作者字段?
找到了。 我的错误在于定义架构。 应该是:
@Schema()
export class Story extends Document {
@Prop()
title: string;
@Prop({ type: MongooseSchema.Types.ObjectId , ref: 'Person' })
author: MongooseSchema.Types.ObjectId
}
经过大量阅读和测试 nestjs 中的 mongoose 引用。我认为可以改进接受的答案。我将分两步展示这一点。第一步是显示 MongooseSchema 的声明,并包括 @illnr 关于作者 属性 使用 Types.ObjectId
而不是 MongooseSchema.Types.ObjectId
.
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { Document, Types, Schema as MongooseSchema } from 'mongoose';
@Schema()
export class Story extends Document {
@Prop()
title: string;
@Prop({ type: MongooseSchema.Types.ObjectId , ref: 'Person' })
author: Types.ObjectId
}
export const StorySchema = SchemaFactory.createForClass(Story);
作为第二步,我认为使用 Person class 作为作者 属性 的类型可以提高可读性,如此处所示。
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { Document, Types, Schema as MongooseSchema } from 'mongoose';
import { Person } from './person.schema'
@Schema()
export class Story extends Document {
@Prop()
title: string;
@Prop({ type: MongooseSchema.Types.ObjectId , ref: 'Person' })
author: Person
}
export const StorySchema = SchemaFactory.createForClass(Story);
None 以上对我有用,我不得不使用 populate()
。参考资料来自 https://dev.to/mossnana/nestjs-with-mongoose-populate-4mo7?signin=true
完整代码和结构示例 users.service.ts
import { User, UserDocument } from 'src/schemas/user.schema';
import { Role, RoleDocument } from 'src/schemas/role.schema';
...
constructor(
@InjectModel(User.name) private userModel: Model<UserDocument>,
@InjectModel(Role.name) private roleModel: Model<RoleDocument>,
private roleService: RolesService
) {}
async findOne(id: string) {
return await this.userModel.findOne({ _id: id }).populate('role', '', this.roleModel).exec();
}
user.schema.ts
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import * as mongoose from 'mongoose';
import { Role } from './role.schema';
export type UserDocument = User & mongoose.Document;
@Schema()
export class User {
@Prop({ required: true, type: String })
email: string;
@Prop({ type: String })
name: string;
@Prop({ type: mongoose.Schema.Types.ObjectId, ref: 'Role' })
role: Role;
}
export const UserSchema = SchemaFactory.createForClass(User);
role.schema.ts
export type RoleDocument = Role & mongoose.Document;
@Schema()
export class Role {
@Prop({ type: String, required: true, unique: true, index: true })
name: string;
@Prop({ type: [String], required: true })
permissions: string[];
}
export const RoleSchema = SchemaFactory.createForClass(Role);