NodeJS and mongoose CastError: Cast to [ObjectId] failed for value

204 Views Asked by At

I am using molecularjs actions to enter data into my database. Primarily I am using NodeJS with mongoose to define models. So far I am able to create a model but when I try to create an one-to-many relation it gives me this error

errors: { 'deliveryParcels.0': CastError: Cast to [ObjectId] failed for value "[{"parcelId":"LHE660851871415","address":"24 E muhafiz town lahore","type":"COD","addressLocation":{"lat":31.4532941,"lng":74.2166403},"customerName":"ALI MALHI","customerPhone":"3314488396","processingStatus":"pending","amount":2500,"vendorOrderId":"other"}]" at path "deliveryParcels.0"

I want both collections rider-tasks and delivery-parcels to be created simultaneously but only the rider-tasks collection gets created but not the delivery-parcels. What am I doing wrong in my schema?

Here are my models

rider-tasks model

import mongoose, { Schema } from "mongoose";
import { getDbConnection } from "../../../utils/db/db-connect";

/* eslint-disable id-blacklist */
import { IRiderTaskModel } from "../interfaces/rider-task.interface";
const RiderTaskSchema: Schema<IRiderTaskModel> = new Schema<IRiderTaskModel>(
    {
        _id: { type: String, required: true, unique: true },
        riderId: { type: String, required: true },
        totalAmount: { type: Number, required: true },
        riderName: { type: String, required: true },
        cityId: { type: String, required: true },
        cityName: { type: String, required: true },
        status: { type: String, required: true },
        adminName: { type: String, required: true },
        adminId: { type: String, required: true },
        createdAt: { type: Date, required: true },
        deliveryParcels: [
            {
                type: Schema.Types.ObjectId,
                ref: "delivery-parcels",
            },
        ],
    },
    { _id: true }
);

const RiderTask = getDbConnection("deliveryManagement").model<IRiderTaskModel>(
    "rider-tasks",
    RiderTaskSchema
);
export { RiderTask };

delivery-parcels

import mongoose, { Schema } from "mongoose";
import { getDbConnection } from "../../../utils/db/db-connect";
import { IDeliveryParcelModel } from "../interfaces/delivery-parcels.interface";
const DeliveryParcelsSchema: Schema<IDeliveryParcelModel> = new Schema<IDeliveryParcelModel>(
    {
        parcelId: { type: String, required: true },
        address: { type: String, required: true },
        addressLocation: {
            lat: { type: Number, required: true },
            lng: { type: Number, required: true },
        },
        customerName: { type: String, required: true },
        customerPhone: { type: String, required: true },
        processingStatus: { type: String, required: true },
        amount: { type: Number, required: true },
        riderTaskId: { type: Schema.Types.String, ref: "rider-tasks" },
        type: { type: String, required: true, enum: ["COD", "NONCOD"] },
        postedStatus: {
            status: { type: String },
            statusKey: { type: String },
            signature: { type: String },
            reason: { type: String },
            checkBoxData: [{ type: String }],
            adminId: { type: String },
            adminName: { type: String },
        },
    }
);

const DeliveryParcels = getDbConnection(
    "deliveryManagement"
).model<IDeliveryParcelModel>("delivery-parcels", DeliveryParcelsSchema);
export { DeliveryParcels };

My service

private async createdRiderTaskHandler(ctx: Context<IRiderTaskModel>) {
    const { params } = ctx;
    const finalData: IParcelData[][] = await Promise.all(
        params.deliveryParcels.map((parcel) =>
            this.broker.call("parcel-data.getParcels", {
                id: parcel.parcelId,
            })
        )
    );
    const wrongParcels: string | any[] = [];
    const check = finalData[0].filter(
        (data) => data.currentStatus.status === "Dispatched"
    )[0];
    if (check) {
        wrongParcels.push(check.parcelId);
        const parcel = wrongParcels.join("\r\n");
        throw new Error(
            'These parcels "' + parcel + '" have already been dispatched'
        );
    }
    const codAmount = params.deliveryParcels
        .filter((data, i) => data.type === "COD")
        .reduce((total, b) => total + b.amount, 0);

    const customId = "RTD-" + Math.floor(100000 + Math.random() * 900000);
    try {
        const taskData = omit({
            ...params,
            _id: customId,
            totalAmount: codAmount,
            forceAssignment: false,
            createdAt: new Date(),
        });

        const data = await RiderTask.create(taskData);
        return { message: data };
    } catch (error) {
        this.logger.error(error);
        return error;
    

   }
}
0

There are 0 best solutions below