在我的应用中,用户可以创建帖子。我想通过引用用户ObjectId
为每个帖子分配一个用户。
发布模型和架构:
const postSchema = new mongoose.Schema({
postImage: {
type: String,
required: true
},
caption: {
type: String
},
user: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
},
date: {
type: Date,
default: Date.now()
}
})
const Post = mongoose.model('Post', postSchema)
用户模型和架构:
const userSchema = new mongoose.Schema({
username: {
type: String,
required: true,
unique: true,
minlength: 4,
maxlength: 50
},
password: {
type: String,
required: true,
minlength: 6,
maxlength: 75
}
})
userSchema.methods.generateAuthToken = () => {
const token = jwt.sign({ _id: this._id }, config.get('jwtPrivateKey'))
return token
}
const User = mongoose.model('User', userSchema)
在我的发布路线中,我应用了以下中间件(身份验证中间件):
module.exports = (req, res, next) => {
const token = req.header('x-auth-token')
if (!token) return res.status(401).send('No token provided')
try {
const decoded = jwt.verify(token, config.get('jwtPrivateKey'))
req.user = decoded
next()
}
catch (ex) {
res.status(400).send('Invalid token')
}
}
发布路线:
router.post('/', [auth, upload.single('postImage')], async (req, res) => {
const post = new Post({
postImage: `http://localhost:3000/${req.file.path}`,
caption: req.body.caption,
user: req.user._id
})
await post.save()
res.send(post)
})
当我向路线提出请求时,我设置了x-auth-token
,并且得到了创建的post对象的响应。但是,在数据库中,尚未设置post对象的user
属性。在创建的post对象上仅设置了以下属性。 _id, date, postImage, caption, __v
。有人知道为什么不将用户设置为属性吗?谢谢。
更新: 这就是我生成附加了_id的jwt令牌的方式:
userSchema.methods.generateAuthToken = () => {
const token = jwt.sign({ _id: this._id }, config.get('jwtPrivateKey'))
return token
}