简体   繁体   中英

MongoDB and nodejs

We have a array of mongodb Documents. Now this array may contain duplicate documents. How to insert these document as it is if document is not there in the collection(each document also have _id inside it). I am continously getting a error for duplicate key for duplicate documents. I am not using mongoose instead I am using mongodb native driver.

const query = { mappingID: id };
await consumerContainer.findOne(query, async (err, item) => {
  try {
    if (err) {
      throw err;
    }
    if (item === null) {
      await consumerContainer.insertOne(result);
    } else {
      console.log('duplicate entries found : ', item._id);
    }
  } catch (error) {
    console.log(error);
  }
});

You are using await and using the callback with findOne .
Try to change your code like this:

const query = { mappingID: id };

try {
  const consumer = await consumerContainer.findOne(query);
  if (!consumer) {
    await consumerContainer.insertOne(result);
  } else {
    console.log('duplicate entries found : ', consumer._id);
  }
} catch (err) {
  console.log(error);
}

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