Node.js 显示帖子';ejs中的用户名

Node.js 显示帖子';ejs中的用户名,node.js,mongoose,ejs,Node.js,Mongoose,Ejs,我正在使用ejs视图引擎制作我的第一个Node.js应用程序。我有两个模型:post和user。我尝试将这两个模型链接在一起,但似乎不知道如何显示用户发布了什么帖子 这是用户模型: // User Schema var UserSchema = mongoose.Schema({ username: { type: String, index:true }, password: { type: String },

我正在使用ejs视图引擎制作我的第一个Node.js应用程序。我有两个模型:post和user。我尝试将这两个模型链接在一起,但似乎不知道如何显示用户发布了什么帖子

这是用户模型:

// User Schema
var UserSchema = mongoose.Schema({
    username: {
        type: String,
        index:true
    },
    password: {
        type: String
    },
    email: {
        type: String
    },
    name: {
        type: String
    },
    facebook : {
            id           : String,
            token        : String
        },
    posts : [{ type: mongoose.Schema.Types.ObjectId, ref: 'Post' }]
});
以下是帖子:

// Post Schema
var PostSchema = mongoose.Schema({
    user: {type: mongoose.Schema.ObjectId, ref: 'User'},
    name: {
        type: String,
        index:true
    },
    text: {
        type: String
    }
});
这是我显示帖子的控制器/路线:

// Post page
router.get('/post', function(req, res){
    req.db.collection('posts').find().toArray((err, result) => {
        if (err) return console.log(err)
        res.render('posts/post', {posts: result, req: req});
    })  
});
现在 如果我的视图文件(ejs)中有此项:

编辑 更新控制器以填充用户。它现在起作用了

// Post page
router.get('/post', function(req, res){
    Post.find().populate('user').exec(function(err, result) {
        if (err) return console.log(err)
        res.render('posts/post', {posts: result});
     })
});

在post模式中引用用户时,需要将Mongoose告知用户。如果不这样做,则在查询结果中只会获得对用户的ObjectId引用

req.db.collection('posts')
  .find()
  .populate('user')
  .toArray((err, result) => {
    // logic here
})  
我认为ejs与此无关,因为它只是渲染引擎


在insert中,您可能会发送所有用户信息,但我不太确定,因为您没有向我们显示insert查询的完整代码。

您是对的。我更新了我的答案,以确保您可以看到更改
{ __v: 0,
 name: 'lol',
 text: 'test',
 user: 
  { _id: d6cf225e,
    username: 'Test',
    email: 'test@test.se',
    name: 'Test',
    __v: 0,
    posts: [],
    facebook: 
      { token: 'TOKENNUMBER'
       id: '23123123' } },
    _id: 2d8afa19fbf6 }
// Post page
router.get('/post', function(req, res){
    Post.find().populate('user').exec(function(err, result) {
        if (err) return console.log(err)
        res.render('posts/post', {posts: result});
     })
});
req.db.collection('posts')
  .find()
  .populate('user')
  .toArray((err, result) => {
    // logic here
})