【问题标题】:Express and Mongoose with MongoDBExpress 和 Mongoose 与 MongoDB
【发布时间】:2014-06-11 22:58:32
【问题描述】:

大家好,我有一个用于创建列表的角色:

文档用户 Json 示例

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

模型用户

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);

模型项目

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

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

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

路由/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 %>

但我没有定义,为什么?我想要项目的名称。

【问题讨论】:

    标签: node.js mongodb express mongoose


    【解决方案1】:

    你应该在你的find查询上调用populate你开始执行它之前:

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

    【讨论】:

      猜你喜欢
      • 2011-09-14
      • 2022-11-10
      • 2015-10-11
      • 2022-09-23
      • 2016-09-23
      • 1970-01-01
      • 2021-03-17
      • 2019-07-11
      • 2020-08-18
      相关资源
      最近更新 更多