mongodb @nestjs/mongoose,使用2个数据库进行虚拟填充

vsikbqxv  于 2023-01-12  发布在  Go
关注(0)|答案(1)|浏览(183)

我正在尝试从 db2 中存在的用户文档填充数据库1中存在的userId字段。
我已经在MongooseModule.ForRootAsync()中定义了connectionName参数,我找不到问题所在。如果我分别从db1db2请求信息,它也会工作。
实际上在console.log(commentPopulated)userId字段只是objectId没有填充字段从用户模式,有时也与某些@Prop().populate()参数应用程序扔给我这个错误:

MissingSchemaError: Schema hasn't been registered for model "User".

使用@nestjs/mongoose装饰器我如何实现这一点?
app.module.ts

MongooseModule.forRootAsync({
  connectionName: 'db1',
  useFactory: () => ({
    uri: process.env.DB1,
    connectionFactory: (connection: { plugin: (arg0: unknown) => void }) => {
      connection.plugin(_)
      connection.plugin(autoPopulate)
      return connection
    },
  }),
}),
MongooseModule.forRootAsync({
  connectionName: 'db2',
  useFactory: () => ({
    uri: process.env.DB2,
    connectionFactory: (connection: { plugin: (arg0: unknown) => void }) => {
      connection.plugin(_)
      connection.plugin(autoPopulate)
      return connection
    },
  }),
}),

comment.module.ts

const commentModule: DynamicModule = MongooseModule.forFeatureAsync([
    {
        name: Comment.name,
        useFactory: () => {
            return CommentSchema
        }
    }
], 'db1')

@Module({
    imports: [commentModule],
    providers: [CommentService, CommentResolver]
})
export class CommentModule { }

x1米11米1x

@Schema({ toJSON: { virtuals: true, getters: true }, toObject: { virtuals: true, getters: true } })
@ObjectType()
export class Comment extends Document {
    @Prop()
    @Field(() => String)
    readonly _id: MongooseSchema.Types.ObjectId

    @Prop({ required: true })
    @Field(() => String)
    text: string

    //TODO: Reference User document from DB2, Comment document exists in DB1
    @Prop({ type: MongooseSchema.Types.ObjectId, virtualpath: User.name, virtuals: true })
    @Field(() => User, { nullable: true })
    userId: MongooseSchema.Types.ObjectId

    @Prop({ type: String, enum: UserType, required: true, default: UserType.Regular })
    @Field(() => UserType, { defaultValue: UserType.Regular })
    userType: UserType

    @Prop({ default: Date.now })
    @Field(() => Date)
    created: Date
}

export const CommentSchema = SchemaFactory.createForClass(Comment)

user.module.ts

const userModule: DynamicModule = MongooseModule.forFeatureAsync([
  {
    name: User.name,
    useFactory: () => {
      return UserSchema
    },
  },
], 'db2')

@Module({
  imports: [userModule],
  providers: [UserService, UserResolver]
})
export class UserModule { }

user.schema.ts

@Schema()
@ObjectType()
export class User extends Document {
    @Prop()
    @Field(() => String)
    readonly _id: MongooseSchema.Types.ObjectId

    @Prop({ required: true })
    @Field(() => String)
    firstName: string

    @Prop({ required: true })
    @Field(() => String)
    lastName: string

    @Prop({ required: true })
    @Field(() => String)
    email: string
}

export const UserSchema = SchemaFactory.createForClass(User)

comment.service.ts

@Injectable()
export class CommentService {
    constructor(@InjectModel(Comment.name, 'db1') private readonly model: Model<Comment>) { }
    async getComments() {
        const commentPopulated = await this.model.findById('63b8608c7d4f880cba028bfe').populate('userId')
        console.log(commentPopulated)
        return commentPopulated
    }
}

我试过在@Prop()装饰器上随机玩参数,没有成功,我认为有问题,也玩了.populate()函数参数。

xdnvmnnf

xdnvmnnf1#

const db1 = mongoose.createConnection('mongodb://127.0.0.1:27000/db1');
const db2 = mongoose.createConnection('mongodb://127.0.0.1:27001/db2');

const userSchema = new Schema({...});
const User= db2.model('User', userSchema);

const commentSchema = new Schema({
...
user: {
type: ObjectId,
ref: User // `ref` is a **Model class**, not a string
}
});
const Comment = db1.model('Comment', commentSchema);

const comments = await Comment.
find().
populate('user');

此示例来自mongoose docs跨数据库填充

相关问题