mongoose - 如何打印出嵌套在猫鼬模式中的对象?
问题描述
我想打印出用户拥有的每个帖子。但是,嵌套在用户内部的帖子对象没有按我的意愿输出。这是用户架构:
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 中加载嵌套对象,您需要使用 populate 函数:
- 猫鼬文档是:Moongose 文档
在您的情况下,当您搜索用户时,您需要填充帖子。
User.
findOne({ _id: '507f167e810c14739de860ef' }).
populate('posts').
exec(function (err, user) {
...
});
- 如果您想为所有调用重现此行为,您可以使用此库配置您的架构:https ://www.npmjs.com/package/mongoose-autopopulate 。
推荐阅读
- filemaker - FileMaker 18 中没有自定义函数选项
- asynchronous - 在异步 Rust 中,如何实现 poll 的包装器?
- java - 我正在尝试获取审计 list.in 后端我正在使用 python.python2 我正在获取数据但在 python3 中我不能
- firebase - FirebaseRTC 登录失败
- pdf - 如何使用 pdf.js 从 pdf 中提取 Bezeir 曲线信息?
- c++ - 无法从朋友函数访问类的私有成员?'ostream' 不是'std' 的成员?
- httpd.conf - 即使在应用程序部署之后,如何永久编辑 httpd.conf 以使 apache 2.4 中的更改发生?
- c++ - 为 Sublime Text 的 g++ 构建和运行设置超时?
- android - 如何在 Android 的改造 Body 中仅发布 Array
- javascript - 无法在节点 API 中获取请求正文