简体   繁体   English

MongoDB 模型未通过模式嵌入对象连接

[英]MongoDB Models not connecting through Schema embedded objects

I am working on a blog app.我正在开发一个博客应用程序。 Here one user has a one-to-many relationship with posts.After creating the basic CRUD I wanted to make a profile page featuring all the posts of a single User.在这里,一个用户与帖子具有一对多的关系。在创建基本的 CRUD 之后,我想制作一个个人资料页面,其中包含单个用户的所有帖子。 I am following all the steps but still when I fetch all users I get empty array of Post.我正在遵循所有步骤,但是当我获取所有用户时,我仍然得到空的 Post 数组。

And also I am trying to get user name in each post instead of only ID.而且我还试图在每个帖子中获取用户名,而不仅仅是 ID。 I am using Populate but still getting only user id back.我正在使用 Populate 但仍然只返回用户 ID。

 router.get('/', auth, async (req, res) => { try { const Posts = await Post.find().sort({ date: -1 }).populate('users'); res.json(Posts); } catch (err) { console.error(err.message); res.status(500).send('Server Error'); } });

Here's my user schema这是我的用户架构

 const mongoose = require('mongoose'); const UserSchema = new mongoose.Schema({ name: { type: String, required: true }, posts: [ { type: mongoose.Schema.Types.ObjectId, ref: 'Post' } ], email: { type: String, required: true, unique: true }, password: { type: String, required: true }, date: { type: Date, default: Date.now } }); const User = mongoose.model('user', UserSchema); module.exports = User;

Here's Post Schema这是帖子架构

 const mongoose = require('mongoose'); const PostSchema = new mongoose.Schema({ user: { type: mongoose.Schema.Types.ObjectId, ref: 'User' }, title: { type: String, required: true }, content: { type: String, required: true }, date: { type: Date, default: Date.now } }); const Post = mongoose.model('post', PostSchema); module.exports = Post;

I am following all the steps but still when I fetch all users I get empty array of Post我正在遵循所有步骤,但是当我获取所有用户时,我仍然得到空的 Post 数组

When you add a new post you must also update the posts field of the userSchema :添加新帖子时,您还必须更新userSchemaposts字段:

const newPost = await Post.insert(/* post */);
await User.findOneAndUpdate({ _id: newPost.user }, { $push: { posts: newPost._id }, { new: true });

And also I am trying to get user name in each post instead of only ID.而且我还试图在每个帖子中获取用户名,而不仅仅是 ID。 I am using Populate but still getting only user id back我正在使用 Populate 但仍然只返回用户 ID

Try .populate('user');尝试.populate('user'); without s没有s

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM