How to Save non-duplicate (unique) Documents in MongoDB via Mongoose — Node.js

Mishka
2 min readMay 6, 2019

--

How I avoid duplicates in a MongoDB database in my Node.js project with an example

For me, learning even the simplest of things can take time. Mostly because I have trouble searching for it. As I’ve had no formal training in programming, I’m ignorant of a lot of technical terms that would make searching online so much more easier.

So once again I was stuck trying to figure out how to make sure I didn’t save duplicates in my database. This is useful for document titles or objects that you want to be unique. Like a username. If you don’t put up any red tape in your code, then you’ll end up with a lot of duplicates which can cause trouble later.

I’ve added all the code for this example on thiscodeworks.com.

It all comes down to a Javascript if-else statement.

If: Find a match

Using the input from your form, start by searching your database for that data — you can use a findOne method to filter documents. If it turns up with a result, you can then proceed to exit the function without updating the document.

Else: Create a new document

If there are no matches in your database, you can proceed with saving or updating your code however you want to.

Example Code for Saving Unique Documents in MongoDB via Mongoose

Example model:

var mongoose = require(‘mongoose’);
var Schema = mongoose.Schema;

const exampleSchema = new Schema({
title: { type: String , required: true},
content: [{type: String}]
});


var Example = mongoose.model(‘Example’, exampleSchema);
module.exports = Example;

Function in your POST method:

router.post(‘/example’, (req, res, next) => {

var query = req.body.title; //Extract title from input form
Example.findOne({title:query}, function(err, example){
if(err) console.log(err);
if ( example){
console.log(“This has already been saved”);
} else {

var example = new Example(req.body);
example.save(function(err, example) {
if(err) console.log(err);
console.log(“New example created”);
res.redirect(`/`);
});
}
});
});

For further details, view the entire post here.

--

--

Mishka
Mishka

Written by Mishka

Creator of thiscodeworks.com \n Follow me @mishkaorakzai on Twitter. I write at mishka.codes

Responses (5)