【发布时间】:2019-11-29 20:22:26
【问题描述】:
我正在尝试更好地掌握 Express.js,并尝试创建一个简单的博客站点。
我的用户模型很简单:用户名、显示名称和一组帖子。
const userSchema = new Schema({
username: {
type: String,
required: true,
unique: true,
trim: true,
minlength: 3
},
displayname: {
type: String,
required: true,
minlength: 1
},
posts: [{ type: Schema.Types.ObjectId, ref: 'Post' }]
}, {
timestamps: true,
});
我的 Post 模型也是如此:内容和作者。
const postSchema = new Schema({
body: {
type: String,
required: true,
minlength: 1,
maxlength: 140
},
author: { type: Schema.Types.ObjectId, ref: 'User', required: true }
});
我已成功创建新用户并发帖:
[
{
"posts": [],
"_id": "5d32c9474e28f66c08119198",
"username": "Prince",
"displayname": "The Artist",
"createdAt": "2019-07-20T07:56:55.405Z",
"updatedAt": "2019-07-20T07:56:55.405Z",
"__v": 0
}
]
[
{
"_id": "5d34af1ecae7e41a40b46b5a",
"body": "This is my first post.",
"author": "5d32c9474e28f66c08119198",
"__v": 0
}
]
这是我创建用户和发帖的路线
//Create a user
router.route('/create').post((req, res) => {
const username = req.body.username;
const displayname = req.body.displayname;
const newUser = new User({
username,
displayname
});
newUser.save()
.then(() => res.json('New user created!'))
.catch(err => res.status(400).json(`Error: ${err}`));
});
//Create A Post
router.route('/create').post((req, res) => {
const body = req.body.body;
const author = req.body.author;
const newPost = new Post({
body,
author
});
newPost.save()
.then(() => res.json('Created new post!'))
.catch(err => res.status(400).json(`Error: ${err}`));
});
以及我获取用户所有帖子的方法:
//Get all posts by user
router.route('/posts/:id').get((req, res) => {
User.findById(req.params.id)
.populate('posts')
.exec((err, user) => {
if(err) {
res.status(400).json(`Error: ${err}`);
} else {
res.json(user.posts);
}
});
});
每当我查看来自 /users/posts/:id 的响应时,该数组都是空的,但我希望它填充由具有我提供的 ID 的用户发布的帖子?我是否误解了填充的工作原理?
【问题讨论】:
标签: javascript mongodb express mongoose