Mongoose 无法使用JWT在博客文章MERN堆栈中填充作者
我正在尝试创建一个博客网站,使用mernstack和JWT进行身份验证 我的用户模型如下:Mongoose 无法使用JWT在博客文章MERN堆栈中填充作者,mongoose,jwt,mongoose-populate,Mongoose,Jwt,Mongoose Populate,我正在尝试创建一个博客网站,使用mernstack和JWT进行身份验证 我的用户模型如下: const mongoose = require("mongoose"); const { Schema } = mongoose; const UserSchema = Schema({ name: String, username: String, password: String, posts: [{ type: Schema.Types.ObjectId, ref: "Blog"
const mongoose = require("mongoose");
const { Schema } = mongoose;
const UserSchema = Schema({
name: String,
username: String,
password: String,
posts: [{ type: Schema.Types.ObjectId, ref: "Blog" }]
});
module.exports = mongoose.model("User", UserSchema);
blog.post("/", authenticateUsingJwt, (req, res) => {
// Validating the req.body object
const newPost = new Blog({
title: req.body.title,
content: req.body.content,
author: req.user_id
});
newPost.save();
});
我的博客模型如下所示:
const mongoose = require("mongoose");
const { Schema } = mongoose;
const BlogSchema = Schema({
title: String,
content: String,
date: { type: Date, default: Date.now },
author: { type: Schema.Types.ObjectId, ref: "Blog" }
});
module.exports = mongoose.model("Blog", BlogSchema);
我正在使用JWT对创建新博客路径进行身份验证。
登录时,我将向客户端发送一个JWT令牌,并将当前用户的id和名称作为有效负载。
如果从react前端发送的令牌有效,那么我将在验证JWT时将用户id添加到req对象。
即,req对象将有一个用户id字段,以及标题、正文和其他内容
“创建新邮件”路径如下所示:
const mongoose = require("mongoose");
const { Schema } = mongoose;
const UserSchema = Schema({
name: String,
username: String,
password: String,
posts: [{ type: Schema.Types.ObjectId, ref: "Blog" }]
});
module.exports = mongoose.model("User", UserSchema);
blog.post("/", authenticateUsingJwt, (req, res) => {
// Validating the req.body object
const newPost = new Blog({
title: req.body.title,
content: req.body.content,
author: req.user_id
});
newPost.save();
});
当我使用mongodb shell并查看我的用户集合时,我看到posts[]是一个空数组。
如何修复此问题,以便我可以使用填充
User.findOne({ username: "existingUserInDatabase" })
.populate("Blog")
.then(user => res.send(user))
.catch(err => console.log(err));
这段代码从数据库返回用户,但是posts[]是一个空数组。您需要使用Blog而不是Blog进行填充
User.findOne({username:“existingUserInDatabase”})
.populate(“Blog”)//不是“Blog”
.then(用户=>res.send(用户))
.catch(err=>console.log(err));
@user10822859您检查过这个答案吗?请给出一些反馈。很抱歉耽搁了这么长时间。是的,我查过了。我必须填充一个字段名。在我的情况下,这是帖子。非常感谢。