0 points

Save to MongoDB without Duplicates Using Mongoose


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_copy Copy

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");
content_copy Copy

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.