我定义了人物和故事模式:
@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
}
如何使用引用的人员文档填充作者字段?
在对 Nestjs 中的猫鼬参考进行大量阅读和测试之后。我认为已接受的答案可以改进。我将分两步展示这一点。第一步是显示 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 类作为作者属性的类型可以提高可读性,如下所示。
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);
找到了。 我的错误在于定义模式。 应该是:
@Schema()
export class Story extends Document {
@Prop()
title: string;
@Prop({ type: MongooseSchema.Types.ObjectId , ref: 'Person' })
author: MongooseSchema.Types.ObjectId
}
以上对我来说都不起作用,我不得不使用
populate()
。参考来自 https://dev.to/mossnana/nestjs-with-mongoose-populate-4mo7?signin=true
完整代码和结构示例 用户.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();
}
用户.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);
角色.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);
在我的回复中,我定义了预订和任务分配者模式。我使用 UUID(生成唯一字符串)而不是 ObjectID 来覆盖每个 MongoDB 文档的默认 ObjectID。由于taskerID属性,我使用类型为
string
而不是Types.ObjectId
。
预订.schema.ts
import { Prop, Schema, SchemaFactory } from "@nestjs/mongoose";
import mongoose, { HydratedDocument } from "mongoose";
export type BookingDocument = HydratedDocument<Booking>;
@Schema({ collection: "booking" })
export class Booking {
@Prop({ required: true })
_id: string;
@Prop({required: true, type: mongoose.Schema.Types.String, ref: "Tasker"})
taskerID: string;
}
export const BookingSchema = SchemaFactory.createForClass(Booking);
export const BookingModel = {name: Booking.name, schema: BookingSchema};
tasker.schema.ts
import { Prop, Schema, SchemaFactory } from "@nestjs/mongoose";
import { HydratedDocument } from "mongoose";
export type TaskerDocument = HydratedDocument<Tasker>;
@Schema({ collection: "tasker" })
export class Tasker {
@Prop({ required: true })
_id: string;
@Prop({ required: true })
phone: string;
@Prop({ required: true })
name: string;
}
export const TaskerSchema = SchemaFactory.createForClass(Tasker);
export const TaskerModel = {name: Tasker.name, schema: TaskerSchema};
我填充了猫鼬参考,如下例所示。
预订.service.ts
import { Injectable } from "@nestjs/common";
import { InjectModel } from "@nestjs/mongoose";
import { Booking, BookingDocument } from "../db-module/schemas/booking.schema";
import * as mongoose from "mongoose";
import { Tasker, TaskerDocument } from "../db-module/schemas/tasker-user.schema";
@Injectable()
export class BookingService {
constructor(
@InjectModel(Booking.name)
private bookingModel: mongoose.Model<BookingDocument>,
@InjectModel(Tasker.name)
private taskerModel: mongoose.Model<TaskerDocument>
) {}
async findById(id: string): Promise<Booking> {
const Booking = await this.bookingModel.findOne({ _id: id }).populate(
"taskerID",
"",
this.taskerModel,
).exec();
return Booking.toJSON();
}
}