I write some nodejs code to make a to do list, using express, ejs and mongoose when i write this code:
const itemShema = new mongoose.Schema({
name: String
})
const Item = mongoose.model('Item', itemShema);
const item1 = new Item({
name: 'drink water'
})
const defaults = item1;
const listShema = mongoose.Schema({
name: String,
Items: [itemShema]
});
const List = mongoose.model('List', listShema);
app.get('/:custom', function(req,res){
let routes = req.params.custom;
List.findOne({name:routes}, function(err, showItem){
if (err) console.log(err);
else{
if (!showItem){
const listName = new List({
name: routes,
Items: defaults
});
listName.save();
console.log(routes);
res.redirect("/" + routes);
}
else {
res.render('list', {titleList: routes, items: showItem.Items});
}
}
});
});
Basically i want to create a dynamic url and get value of what i triggle by using req.params.custom. Then i create new list (example: /home) and check if that list exist data by findOne({name:routes}. If not exist -> create default data and redirect, else -> res.render ejs file that i set tiltle is routes and items is showItem.Items
=> The problem is when i run this code, it create 2 same databases name:'home', Items: ['drink water'].
I have no clue that why it create 2 and how to fix it, i just want to add 1 default data Please help me!