These are chat archives for Automattic/mongoose

23rd
Sep 2018
Tobias Løfgren
@tobloef
Sep 23 2018 12:39

Hey there. I have a document with two properties, products and catalog. When I'm creating catalog, based on the products property, I sometimes push one of the products from products to an array in catalog. When printing the product's properties right when inserting it, I see everything, the title, price and so on. But when I later query catalog in the database, all I see is an id referring to product object inside the original document's products array.

Anyone know what's up with that? I assume it's some kind of optimization on Mongoose's part, to prevent duplication, but in this instance I'm fine with the data being duplicated, since I don't want to query the products property for each product in the catalog.

Kev
@lineus
Sep 23 2018 12:41
@tobloef what does your schema look like?
Tobias Løfgren
@tobloef
Sep 23 2018 12:44
Here are abbreviated versions of the three relevant schemas:
const CustomerSchema = new Schema({
    products: [ProductSchema],
    catalog: ProductCategorySchema,
});

const ProductSchema = new Schema({
    title: String,
    category: ProductCategorySchema
});

const ProductCategorySchema = new Schema({
    title: String,
    products: [new Schema({
        title: String,
    })]
});
ProductCategorySchema.add({subCategories: [ProductCategorySchema]});
Tobias Løfgren
@tobloef
Sep 23 2018 13:00
I think you're right about it being something with the Schemas, since these two console.log statements give different results:
const generatedCatalog = generateCatalog(customer.products);
console.log(generatedCatalog);
customer.catalog = generatedCatalog;
console.log(customer.catalog);
But to me, the Schemas I posted above seems correct, so I'm thinking there's something about Mongo/Mongoose I don't know, that's causing this.
Kev
@lineus
Sep 23 2018 13:13
@tobloef I'll play around with it and see if I can sort it out.
Tobias Løfgren
@tobloef
Sep 23 2018 13:13
I think I have narrowed it down
It's not a bug with the code posted above, I'll give an explanation of the bug in a bit. I think it's either babel or mongoose that's not handling spread operators correctly in this case
Tobias Løfgren
@tobloef
Sep 23 2018 13:22
Alright, I figured it out. Turns out I was totally wrong. This was caused by a circular reference in one of the schemas (not shown in the abbreviated version), that only loaded after the schema for ProductCategorySchema.products had already been created, even though ProductCategorySchema used it. I fixed it by extracting the object that both files in the circular dependencies depended on, out into another module.
Thanks for leading me in the right direction @lineus 👍
Kev
@lineus
Sep 23 2018 13:23
@tobloef cool, I'm glad you got it sorted out.
glad I could help :smile: