我的代码中有3条路由,分别是用户,产品和订单。 我使用jwt并为用户生成令牌,我想将订单分配给令牌所有者。 这是我的订单模型:
var mongoose = require('mongoose');
var orderSchema = mongoose.Schema({
_id: mongoose.Schema.Types.ObjectId ,
product: {type: mongoose.Schema.Types.ObjectId, ref: 'Product'},
quantity: {type: Number , default: 1},
user_name: String
});
module.exports = mongoose.model('Order', orderSchema);
这是我的中间件,用于检查Authenticate(它是作为checkAuth导入的):
module.exports = (req,res,next) => {
try {
var decoded = jwt.verify(req.headers.token, secretjwt);
req.userData = decoded;
next();
} catch (error) {
return res.status(401).json({
'error': 'Auth Failed',
'details': error.message
});
}
这是我的用于添加订单的帖子api,我应该写什么作为user_name将其分配给用户(我不想将用户名作为正文参数)?
router.post('/newOrder', checkAuth, (req,res,next) => {
var order = new Order({
quantity: req.body.quantity,
product: req.body.productId,
user_name: // WHAT SHOULD IT BE?
});
order.save()
.then(result => {
res.status(200).json(result);
})
.catch(err => {
res.json(200);
});
});
提前致谢!
答案 0 :(得分:0)
而不是
req.userData =已解码 放 req.body.userData =已解码
并将user_name:req.body.userData放入以下片段
router.post('/newOrder', checkAuth, (req,res,next) => {
var order = new Order({
quantity: req.body.quantity,
product: req.body.productId,
user_name: // WHAT SHOULD IT BE?
});
order.save()
.then(result => {
res.status(200).json(result);
})
.catch(err => {
res.json(200);
});
});