Search code examples
angularmongooseassociationsmongoose-schemamongoose-populate

Mongoose associations print in ngFor


I have this user.js model

const userSchema = new Schema({

    name: String,
    ...
    skills: [{
        type: Schema.Types.ObjectId,
        ref: 'skill'
    }]
})

and the skill.js model

const skillSchema = new Schema({
     name: String,
     user: {
         type: Schema.Types.ObjectId,
         ref: 'user'
     },
})

When i am getting all the users in Angular, in html i do:

<div *ngFor="let user of arrUsers">
     ...
     <span *ngFor="let skill of user.skills">
           ******{{PRINT skill name}}******
     </span  

</div>

User in mlab is like this:

{
    "name": "a user name"
    "skills": [
        {
            "$oid": "5c17a4269ef5b511ece55446"
        }
    ],
}

and skills:

{
    "_id": {
        "$oid": "5c17a4269ef5b511ece55446"
    },
    "name": "JAVA",
    "user": {
        "$oid": "5bf44809a15006343bc95718"
    },
    "__v": 0
}

in user controller i get the users like this:

findAll: (req, res) => {
    User.find()
        .then(users => {
            res.json(users);
        }).catch(err => {
            res.status(500).send({
                msg: err.message
            });
        });
},

and the skills array of a user in arrUsers console logs this:

... skills: Array(3)

0: "5c18dd0084a030698e17cd40"

1: "5c18dd0384a030698e17cd42"

2: "5c18dd0584a030698e17cd43" ...

Should i populate skills in findAll with some way?

What is the best way to print skill name?

SOLUTION

I had to do User.find().populate('skills') in my controller

Thanks to Zlatko answer


Solution

  • You need to populate the skills on querying it.

    Something like:

    db.users.get(query).populate('skills')
    

    Then your skills array should be populated.