0

I have a GET request for getting a library with this schema below.

const usergameSchema = new mongoose.Schema({
itemId: {
    type: Number,
    required: true,
    default: 1
},
gameId: {
    type: String,
    required: true
},
added_at: {
    type: Date,
    default: Date.now
}
});

const librarySchema = new mongoose.Schema({
    userId: {
        type: String,
        required: true
    },
    userGames: usergameSchema,
    created_at: {
        type: Date,
        default: Date.now
    }
});

The GET request http://localhost:3000/libraries/<user_id> finds the data by user id. Here is my code for the request.

router.get('/:id', verify, async (req, res) => {
const library = await Libraries.find({ userId: req.params.id });
res.json(library);
});

The request only returns this response below. It did not include the userGames field that I also need to get.

[
{
    "_id": "605219f936f65522c4d62f2e",
    "userId": "605219f936f65522c4d62f2d",
    "created_at": "2021-03-17T15:02:17.298Z",
    "__v": 0
}
]

How do I get the userGames field?

1 Answers1

0

You can do this by populating usergameSchema.

You can try to populate usergameSchema in your query :

Code :

Libraries.find({ userId:req.params.id})
.populate('usergameSchema').exec(function(err,post){
    console.log(post);
    console.log(post.User);
})
Hemakumar
  • 639
  • 9
  • 24