带有 typegoose 的 mongoose 返回 null 以供引用与有效的 objectId [英] mongoose with typegoose returns null for reference with valid objectId

查看:48
本文介绍了带有 typegoose 的 mongoose 返回 null 以供引用与有效的 objectId的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用库 https://github.com/szokodiakos/typegoose 来创建猫鼬模型.

I am using the library https://github.com/szokodiakos/typegoose to create mongoose models.

项目.ts

export class Item extends Typegoose { }

const ItemModel = new Item().getModelForClass(Item);
export default ItemModel;

用户.ts

import { InventoryItem } from "./InventoryItem";

export class BagItem extends Typegoose {
  @prop({ ref: Item })
  Item?: Ref<Item>;

  @prop()
  Quantity: Number;
}

export class User extends Typegoose {
  @arrayProp({ items: BagItem })
  Bag?: BagItem[];
}

export const BagItemModel = new BagItem().getModelForClass(BagItem);
const UserModel = new User().getModelForClass(User);

export default UserModel;

当我尝试填充该项目时,该项目为空.但是使用与常规猫鼬模型相同的数据库,我可以填充 BagItem 中的 Item 字段.

When i try to populate the Item, the item is null. But using the same database with regular mongoose models i am able to populate the Item field in BagItem.

app.ts

UserModel.findById(req.user._id).then((user: any) => {
  return user.populate("Bag.Item").execPopulate();
}).then((bagPopulatedUser: User) => {
  console.log("The bag", bagPopulatedUser.Cart);
}).catch((err: MongoError) => {
  console.log(err);
});

推荐答案

原来我需要指定模型并且它可以工作.

Turns out i needed to specify the model and it works.

UserModel.findById(req.user._id).then((user: any) => {
  return user.populate({
    path: "Bag.Item",
    model: "Item"
    }).execPopulate();
}).then((bagPopulatedUser: User) => {
  console.log("The bag", bagPopulatedUser.Cart);
}).catch((err: MongoError) => {
  console.log(err);
});

这篇关于带有 typegoose 的 mongoose 返回 null 以供引用与有效的 objectId的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆