如何打印出嵌套在猫鼬模式内的对象?

时间:2018-07-10 21:26:51

标签: mongoose

我想打印出用户的每条帖子。但是,嵌套在用户内部的post对象不会按我的要求输出。这是用户架构:

var mongoose = require("mongoose");
var passportLocalMongoose = require("passport-local-mongoose");

var UserSchema = new mongoose.Schema({
    username: String,
    password: String,
    profile_picture: String,
    about: String,
    posts: [
      {
         type: mongoose.Schema.Types.ObjectId,
         ref: "post"
      }
    ],
    /*
    friends: [
      {
         type: mongoose.Schema.Types.ObjectId,
         ref: "friend"
      }
   ],
   relationship_status: { type: String, enum: ['Open', 'Closed', 'Pending'] }*/
});

UserSchema.plugin(passportLocalMongoose);

module.exports = mongoose.model("User", UserSchema);

这是发布模式:

var mongoose = require("mongoose");

var PostSchema = new mongoose.Schema({
    title: String,
    image: String,
    description: String,
});

module.exports = mongoose.model("post", PostSchema);

这是我以前打印出来的内容:

<% user.posts.forEach(function(post){ %>
    <h1><%= post.title %></h1>
    <p><%= post.description %></p>
    <h2><%= post.image %></h2>
<% }) %>

这似乎不起作用,但是当我尝试打印出id(post._id)时,它会打印出每个帖子的ID。我该怎么办?

1 个答案:

答案 0 :(得分:0)

对于在猫鼬内部加载嵌套对象,您需要使用填充函数:

以您为例,当您找到用户时,您需要填充帖子。

 User.
  findOne({ _id: '507f167e810c14739de860ef' }).
  populate('posts').
  exec(function (err, user) {
    ...
  });