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
}
})
}