Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
johnwick2614 opened this issue Jul 31, 2020 · 0 comments
Open

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

johnwick2614 opened this issue Jul 31, 2020 · 0 comments

Comments

@johnwick2614
Copy link

johnwick2614 commented Jul 31, 2020

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant