for example the model is
var UserSchema = Schema({
firstName: {
type: String,
required: true
},
secondName: String,
lastName: {
type: String,
required: true
},
email: {
type: String,
unique: true,
required: true
},
password: {
type: String,
required: true
},
status: {
type: String,
required: true
},
roles: [{
type: Schema.ObjectId,
ref: 'Role'
}],
publications: [{
title: {
type: String,
},
description: String,
status: {
type: String,
},
createdAt: {
type: Date
},
updatedAt: {
type: Date,
default: Date.now()
},
pictures: [{
name: String
}],
categories: [{
type: Schema.Types.ObjectId,
refPath: 'Category.subcategories'
}],
the category model is
var CategorySchema = Schema({
name: String,
subcategories: [{
name: String
}]
});
the user has publications and each publication has several categories
categories: [{
type: Schema.Types.ObjectId,
refPath: 'Category.subcategories'
}],
however it does not work.
the json of users is
"users": [
{
"roles": [],
"publications": [
{
"updatedAt": "2018-04-30T03:23:11.921Z",
"categories": [
"5ae4a8b0a7510e3bd80917db",
"5ae4a8b0a7510e3bd80917da"
],
...
and the category one is
{
"categories": [
{
"subcategories": [
{
"_id": "5ae4a8b0a7510e3bd80917db",
"name": "Decoracion"
},
{
"_id": "5ae4a8b0a7510e3bd80917da",
"name": "Electrodomésticos"
},
{
"_id": "5ae4a8b0a7510e3bd80917d9",
"name": "Cocina"
},
{
"_id": "5ae4a8b0a7510e3bd80917d8",
"name": "Muebles"
}
],
"_id": "5ae4a8b0a7510e3bd80917d7",
"name": "Hogar",
"__v": 0
...
the controller is
User.populate(users, {
path: 'publications.categories'
}, (err, users) => {
if (err) {
res.status(500).send({
message: "Error en la peticion"
});
return;
}
if (!users) {
res.status(404).send({
message: "User no encontrado"
});
return;
}
res.status(200).send({
users
});
however it does not populate the categories.
I have seen that he is link
Dynamic References
var userSchema = new Schema({
name: String,
connections: [{
kind: String,
item: { type: ObjectId, refPath: 'connections.kind' }
}]
});
var organizationSchema = new Schema({ name: String, kind: String });
var User = mongoose.model('User', userSchema);
var Organization = mongoose.model('Organization', organizationSchema);
however it does not populate. It only shows the id of the categories.