What I want to do is to create a subscription for a particular shop. I am getting the shop owner ID from the bearer token already, I just need to pass the shop ID into the db document. I am getting the error below when I send shop_id as request body in mongoose:
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-
This is my 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"
}
and route is:
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,
});
});
Shop Schema:
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",
},
});
CodePudding user response:
You're trying to push the whole subscription object to the subscriptions array in the shop, try pushing only the id of the subscription.
Can you post the "Shop" model as well?