繁体   English   中英

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

[英]MongoDB Models not connecting through Schema embedded objects

我正在开发一个博客应用程序。 在这里,一个用户与帖子具有一对多的关系。在创建基本的 CRUD 之后,我想制作一个个人资料页面,其中包含单个用户的所有帖子。 我正在遵循所有步骤,但是当我获取所有用户时,我仍然得到空的 Post 数组。

而且我还试图在每个帖子中获取用户名,而不仅仅是 ID。 我正在使用 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'); } });

这是我的用户架构

 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;

这是帖子架构

 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;

我正在遵循所有步骤,但是当我获取所有用户时,我仍然得到空的 Post 数组

添加新帖子时,您还必须更新userSchemaposts字段:

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

而且我还试图在每个帖子中获取用户名,而不仅仅是 ID。 我正在使用 Populate 但仍然只返回用户 ID

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

暂无
暂无

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

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