0

I have a collection of items which all have serial numbers and other fields attached to them. A document looks like this

{
    _id: ObjectId(),
    serialNum: "123456789",
    ...otherfields
}

I want to insert a new document but only if none of the existing documents match the serialNum field.

I currently use the approach below, but it requires me grabbing the entire collection, looping through it, and then performing the insert. Is there any alternative method that I could be using as this is quite slow on my large collection

Current code:

const insertItems = (newItem) => {

     const itemsCollection = mongodb.db("database").collection("customers");
     
     itemExists = false;
    
     itemsCollection.find({}).toArray()
     .then((items) => {
          for(let i = 0; i < items.length; i++){
              if(items[i].serialNum == newItem.serialNum){
                   itemExists = true
              }
          }
     })
     .then(() => {
          if(itemExists){
               //error here
          } else {
               //insert new item
          }
     })
}
juicy89
  • 448
  • 5
  • 14

2 Answers2

0

instead of looping all collection why not fetch only one which has that serial no as:

const insertItems = (newItem) => {

 const itemsCollection = mongodb.db("database").collection("customers");

 itemExists = false;

 itemsCollection.find({serialNum:newItem.serialNum}).toArray()
 .then((items) => {
      if(items.length){
         itemExists=true
      }
 })
 .then(() => {
      if(itemExists){
           //error here
      } else {
           //insert new item
      }
 })
}
sushant mehta
  • 1,244
  • 1
  • 7
  • 13
0

Try this code

    const insertItems = (newItem) => {

         const itemsCollection = mongodb.db("database").collection("customers");
         itemsCollection.update({serialNum:newItem.serialNum},{
         // New fields which you want to insert or update
         },{upsert: true})
         .then((items) => {
             console.log(item);
         }).catch((err)=>{
            // error here
         })
     }
Rahul kumar
  • 116
  • 7