Skip to content

How to update document and sub documents with nodejs? #11

@johnmw1

Description

@johnmw1

My Entities with sub documents in MongoDB

@Entity()
@Unique(["orderNumber"])
export class Orders {
  @ObjectIdColumn()
  id: ObjectID;
  @Column()
  @Length(4, 10)
  orderNumber: string;
  @Column(type => Product)
  product: Product[];
  @Column()
  @Length(1, 50)
  totalAmount: string;
  @ObjectIdColumn()
  dealerId: ObjectID;
  @ObjectIdColumn()
  employeeid: ObjectID;
  @Column()
  @CreateDateColumn()
  createdAt: Date;
  @Column()
  @UpdateDateColumn()
  updatedAt: Date;
  order: Product;
}

@Entity()
export class Product {
  @PrimaryColumn()
  name: string;
  @Column()
  quantity: string;
  @Column()
  productAmount: string;
  constructor(name: string, quantity: string, productAmount: string) {
    this.name = name;
    this.quantity = quantity;
    this.productAmount = productAmount;
  }
}

NodeJs class to update

static editOrder = async (req: Request, res: Response, next: NextFunction) => {
const id = req.params.id;
const letAllProducts = req.body;
let { totalAmount, dealerId } = req.body;

const productRepository = getRepository(Product);
const orderRepository = getRepository(Orders);
let order: Orders;
try {
  await orderRepository.findOneOrFail(id);
} catch (error) {
  res.status(404).send("Order not found");
  return;
}
order.product = [];
for (let i of letAllProducts.product) {
  order.product.push(new Product(i.name, i.quantity, i.productAmount));
};
order.totalAmount = totalAmount; order.dealerId = ObjectId(dealerId);
const errors = await validate(order);
if (errors.length > 0) {
  res.status(400).send(errors);
  return;
}
try {
  await orderRepository.save(order);
} catch (e) {
  res.send(e);
  return;
}
res.status(200).send("Order updated successfully");

};

UnhandledPromiseRejectionWarning: TypeError: Cannot set property 'product' of undefined!

ps: i am noob. new to coading. Help much appreciated

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions