In MongoDB sometimes you want to create a simple relationship between two schemas. It's very easy when you want to create OneToMany and populate the side of ManyToOne. The problem is when you want to populate the other side.
Explanation:
class UserSchema {
products: ProductSchema[]
}
class ProductSchema {
user: UserSchema
}
UserSchema.populate('products') // Will bring an empty array
ProductSchema.populate('user') // Will bring the user object owner from that product
To solve this empty array updateOneToMany function needs to be implemented and will receive three parameters:
- The id of the main model that is going to be updated
- The relationId of the relation that needs to be pushed to the array
- The relationName inside the main model schema to access the object
Example:
class UserSchema {
products: ProductSchema[]
}
class ProductSchema {
user: UserSchema
}
const user = new UserSchema()
const product = new ProductSchema({ user })
await this.userRepository.updateOneToMany(user.id, product.id, 'products')
UserSchema.populate('products') // Will bring an array with all user products
ProductSchema.populate('user') // Will bring the user object owner from that product
In MongoDB sometimes you want to create a simple relationship between two schemas. It's very easy when you want to create OneToMany and populate the side of ManyToOne. The problem is when you want to populate the other side.
Explanation:
To solve this empty array updateOneToMany function needs to be implemented and will receive three parameters:
Example: