John Staurt
John Staurt

Reputation: 225

mongoose with typegoose returns null for reference with valid objectId

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

Upvotes: 1

Views: 3530

Answers (2)

Kip
Kip

Reputation: 109493

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.

Upvotes: 0

John Staurt
John Staurt

Reputation: 225

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

Upvotes: 3

Related Questions