简体   繁体   中英

MongoDB: findOne not working as expected?

I'm creating an API to my database of coins and I don't want to add duplicate coins to my database so I've created this line of code in my function

const addCoin = async (req, res) => {


const { coinId, seconds, bidAmount } = req.body;
  console.log(coinId);

  const coinExists = await Coin.findOne({ coinId });
  console.log(coinExists);
  if (coinExists) {
    res.status(400).send({ message: 'Coin Exists Bad Request' }); // bad request
    throw new Error('Coin already exists');
  }

In my Postman I am inputting a different coinId in the request body and I am getting the error that Coin Exists? Is findOne here not working as expected?

Confused. Thanks

Ahh after some documentation reading I have to specify which property in the Coin Model I want it to find specifically so in this case I did

Coin.find({ itemId: coinId})

Since in my model its defined as itemId but user input is coinId

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM