Austin
Austin

Reputation: 103

MongoDB insert without duplicates

Right now I am running mongodb and I just realized, I am inserting into collections and I am not sure if I am preventing duplicates. Here is how I am inserting:

function insertCompanies(companyID, companyURL, companyAppID) {
    MongoClient.connect(url, function(err, db) {
        if (err) {
            console.log(err);
        } else {
            console.log("We are connected");
        }

        var collection = db.collection('Companies');
        var company = {
            "companyProfileID": companyID,
            "url": companyURL,
            "appID": companyAppID
        };
        collection.insert(company, function(err, result) {
            if (err) {
                console.log(err);
            } else {
                console.log(result);
            }
        });
        db.close();
    });
}

I am using NodeJS. When a user calls the insertCompanies method, if the company already exists (via companyID or URL), it seems like the collection allows duplicates.

Is there a different insert function that prevents duplicates? I looked around and could not find a straight forward solution tailored to me.

Upvotes: 4

Views: 11713

Answers (2)

Dan Nagle
Dan Nagle

Reputation: 5425

The answer is not to insert, instead use update. The update() method either modifies the fields in existing documents or replaces an existing document entirely.

Upvotes: 1

cjungel
cjungel

Reputation: 3791

Instead of db.insert() you should use db.update() and specify $upsert: true.

https://docs.mongodb.com/v3.2/reference/method/db.collection.update/

Upvotes: 5

Related Questions