1
const { MongoClient } = require("mongodb");
const url =
  "mongodb+srv://user:password@cluster0.25pjvgx.mongodb.net/products_test?retryWrites=true&w=majority";
  
  const createProduct = async (req, res, next) => {
    const newProduct = {
      name: req.body.name,
      price: req.body.price
    };
    const client = new MongoClient(url);
  
    try {
      await client.connect();
      const db = client.db();
      const result = db.collection('products').insertOne(newProduct);
    } catch (error) {
      return res.json({message: 'Could not store data.'});
    };
    client.close();
  
    res.json(newProduct);
  };
  
  const getProducts = async (req, res, next) => {};
  
  exports.createProduct = createProduct;
  exports.getProducts = getProducts;

send-- { "name":"apple", "price": 99 }

output- { "message": "Could not store data." }

Where is the problem? I try to send the data to the database. But it doesn't work I can not find. please help me.

Joe
  • 25,000
  • 3
  • 22
  • 44
Shuvo Roy
  • 11
  • 2

1 Answers1

0

i used await before db.collection('products').insertOne(newProduct).It works for me

Hojat
  • 31
  • 1
  • 6