如何在将值插入数据库之前检查从 api 接收的数据中是否已存在值

How to check if value already exists in the data received from api before inserting it into db

我很难尝试将从 api 接收到的数据写入数据库。 我成功获取数据,然后必须将其写入 db。重点是检查引用是否已经存在于我的 collection 中。 我正在处理的问题是每个值都被插入到我的 collection 中,与它是否存在无关。

 const { MongoClient } = require('mongodb')

 const mongoUrl = 'mongodb://localhost/kanye_quotes'

 async function connectToDb() {
      const client = new MongoClient(mongoUrl, { useNewUrlParser: true })
      await client.connect()
      db = client.db()
 }

 async function addQuote(data) {
 await connectToDb()
 try {
    const collection = db.collection('quotes')
    let quotes = [];
    quotes = await collection.find({}).toArray()

    if (quotes = []) { // I added this piece of code because if not check for [], no values will be inserted
        collection.insertOne(data, (err, result) => {
            if (err) {
                return
            }
            console.log(result.insertedId);
            return
        })
    }

    quotes.forEach(quote => {
        if (quote.quote !== data.quote) { // I compare received data with data in collection, it actually works fine(the comparison works as it supposed to)

            collection.insertOne(data, (err, result) => {
                if (err) {
                    return
                }
                console.log(result.insertedId);
            })
        } else console.log('repeated value found'); // repeated value gets inserted. Why?
    })
 }
  catch (err) {
    console.log(err)
 }
}

您好,最好在您的架构上设置 unique: true indexing。这样你就不会有重复的值。