![](/img/trans.png)
[英]How do I send post request with json body where the body only contains a string not a key value pair?
[英]How do I post ObjectId as request body in mongoose?
我想做的是为特定商店创建订阅。 我已经从不记名令牌中获取了店主 ID,我只需要将商店 ID 传递到 db 文档中。 当我在 mongoose 中将 shop_id 作为请求正文发送时,出现以下错误:
reason: CastError: Cast to ObjectId failed for value "{
subscription: {
title: 'Shaving',
sub_type: 'normal',
subscribers: [],
status: 'active',
unit_price: 250,
monthly_units: 0,
total_units: 0,
total_amount: 0,
shop_id: new ObjectId("6331936ee4e905ef38770cca"),
_id: new ObjectId("6331afa812cf6caff2a7c953"),
createdAt: 2022-09-26T13:56:56.376Z,
updatedAt: 2022-09-26T13:56:56.376Z,
__v: 0
}
}" (type Object) at path "subscriptions"
at ObjectId.cast (C:\Users\Micholusanya\Documents\codes\barbify-
这是我的 model:
title: {
type: String,
required: true
},
sub_type: {
type: String,
enum: ['vvip', 'vip', 'normal', 'student'],
default: 'normal'
},
subscribers: [
{
type: Schema.Types.ObjectId,
ref: "User"
}
],
status: {
type: String,
enum: ["active", "disabled"],
default: "active"
},
unit_price: {
type: Number,
default: 0
},
monthly_units: {
type: Number,
default: 0
},
total_units: {
type: Number,
default: 0
},
total_amount: {
type: Number,
default: 0
},
shop_id: {
type: Schema.Types.ObjectId,
ref: "Shop"
}
路线是:
router.post('/', passport.authenticate('jwt'), async (req, res) => {
const userId = req.user._id;
// req.body.user_id = userId;
//check if user
const user = await User.findById(userId);
//check shops
const shop = await Shop.findById(req.body.shop_id);
console.log('Shop', shop);
const subscription = await Subscription.create({
title: req.body.title,
unit_price: req.body.unit_price,
shop_id: shop._id,
});
subscription.save();
await Shop.findByIdAndUpdate(req.body.shop_id, {
$push: { subscriptions: { subscription } },
});
res.status(201).send({
status: 'success',
message: 'Subscription Created Successfully',
data: subscription,
});
});
您正在尝试将整个订阅 object 推送到商店中的订阅数组,尝试仅推送订阅的 id。
您也可以发布“商店”model 吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.