0 works

Save to MongoDB without Duplicates Using Mongoose


dashboard+ Project

Posted by @bravocoder #javascript #nodejs

Step 0: Compile a 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;
content_copyCopy to Clipboard

Step 1: In your router, use the following

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(`/`);
            });
        }
    });
});
content_copyCopy to Clipboard

More details:

This method helps you prevent creating duplicates in your database. It works by first searching the database. If there are no search results, it will create and save a new item.


>> Browse more code snippets

more_vert