【发布时间】:2022-09-28 03:01:27
【问题描述】:
我想做的是为特定商店创建订阅。我已经从不记名令牌中获取了店主 ID,我只需要将商店 ID 传递到 db 文档中。 当我在猫鼬中将 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-
这是我的模型:
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,
});
});
店铺架构:
photo: {
type: String,
required: true,
},
name: {
type: String,
required: true,
},
address: {
type: String,
required: true,
},
city: {
type: String,
},
state: {
type: String,
},
country: {
type: String,
},
shop_phone: {
type: String,
required: true,
},
status: {
type: Boolean,
default: false,
},
income: {
type: Number,
default: 0,
},
withdrawal: {
type: Number,
default: 0,
},
shop_type: {
type: String,
enum: [\'vvip\', \'vip\', \'normal\', \'student\'],
default: \'normal\'
},
subscriptions: [
{
type: Schema.Types.ObjectId,
ref: \"Subscription\",
},
],
transactions: [
{
type: Schema.Types.ObjectId,
ref: \"Transaction\",
},
],
subscribers: [
{
type: Schema.Types.ObjectId,
ref: \"User\",
},
],
subscriberslength: {
type: Number,
default: 0,
},
user_id: {
type: Schema.Types.ObjectId,
ref: \"User\",
},
});
-
你可以添加
req.body.shop_id的值吗? -
我已经注释掉了。它不再在那里做任何工作,因为我实际上需要 shop_id 而不是 user_id
-
好的,我问
req.body.shop_id。另外这条线是不必要的subscription.save(); -
好的。我将删除subscription.save(),但它还没有解决它。 req.body.shop_id 返回一个字符串
6331936ee4e905ef38770cca。 -
您还可以在问题中添加商店模式代码吗?
标签: javascript node.js mongodb express mongoose