首页 > 解决方案 > 如何打印出嵌套在猫鼬模式中的对象?

问题描述

我想打印出用户拥有的每个帖子。但是,嵌套在用户内部的帖子对象没有按我的意愿输出。这是用户架构:

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。我能做些什么?

标签: mongoose

解决方案


要在 mongoose 中加载嵌套对象,您需要使用 populate 函数:

在您的情况下,当您搜索用户时,您需要填充帖子。

 User.
  findOne({ _id: '507f167e810c14739de860ef' }).
  populate('posts').
  exec(function (err, user) {
    ...
  });
  • 如果您想为所有调用重现此行为,您可以使用此库配置您的架构:https ://www.npmjs.com/package/mongoose-autopopulate 。

推荐阅读