Carla Lo Monte
Carla Lo Monte

Reputation: 85

Express and Mongoose with MongoDB

Hy guys, i have a this cose for the created the list:

Document User Json Example

{
    "__v" : 3,
    "_id" : ObjectId("5396e11c13e345570ae174f1"),
    "created" : ISODate("2014-06-10T10:42:36.925Z"),
    "name" : "Project",
    "projects" : [ 
        ObjectId("5396db4f3458c64f09e23ef8"), 
        ObjectId("53982440de337a4e0b3013a4")
    ]
}

Model User

var mongoose = require('mongoose');
var Schema   = mongoose.Schema;

var User = new Schema({
    name    : String,
    projects: {
       type: Schema.Types.ObjectId,
       ref: 'Project'
    },
    created : Date
});

module.exports = mongoose.model('User', User);

Model Project

var mongoose = require('mongoose');
var Schema   = mongoose.Schema;

var Project = new Schema({
    name    : String,
    key     : String,
    description : String
});

module.exports = mongoose.model('Project', Project);

Route/Index.js

exports.index = function (req, res) {
    User.find(function (err, result) {
        res.render('index', {
            title: 'List',
            user: result
        });
    }).populate('projects');
};

Index.ejs

//foreach
<%= user.projects.name %>

but I get undefined, Why? I would like the name of the project.

Upvotes: 0

Views: 103

Answers (1)

JohnnyHK
JohnnyHK

Reputation: 311835

You should call populate on your find query before you start executing it:

User.find().populate('projects').exec(function (err, result) {
    res.render('index', {
        title: 'List',
        user: result
    });
});

Upvotes: 2

Related Questions