Posted by @bravocoder #javascript #nodejs
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
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
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.