簡體   English   中英

如何在 mongoose 中將 ObjectId 作為請求正文發布?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM