mongoose with typegoose returns null for reference with valid objectId

淺唱寂寞╮ 提交于 2021-02-10 18:23:28

问题


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

Item.ts

export class Item extends Typegoose { }

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

User.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;

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);
});

回答1:


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);
});



回答2:


If you need to do this on multiple documents, it's-

const users = await UserModel.find();
await UserModel.populate(users, {path: 'Bag.Item', model: 'Item'});
//now users[i].item is an Item

Although for me I found path: 'Bag.Item' did not work, but path: 'Item' did work. Maybe something changed in past year.



来源:https://stackoverflow.com/questions/49097980/mongoose-with-typegoose-returns-null-for-reference-with-valid-objectid

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!