Search code examples
javascriptnode.jsmongodbmongoosemongoose-schema

I am inserting data if there are no items in the collection. But the data is inserted two or three times in the collection. How to fix this?


I am new to mongoose and node.js and MERN stack. I am inserting data if there are no items in the collection. But the data is inserted two or three times in the collection. How to fix this? list.ejs:-

<%- include('header') %>
    <div class="box" id="heading">
        <h1>
            <%= listTitle %>
        </h1>
    </div>

    <div class="box">
        
        <% newListItems.forEach(item=> { %>
            <div class="item">
                <input type="checkbox">
                <p>
                    <%= item.name %>
                </p>
            </div>
            <% }); %>

                <form class="item" action="/" method="post">
                    <input type="text" name="newItem" placeholder="New Item" autocomplete="off">
                    <button type="submit" name="list" value="<%= listTitle %>">+</button>
                </form>
    </div>

    <%- include('footer') %>

app.js file:-

const express = require('express');
const bodyParser = require('body-parser');
const date = require(__dirname + '/date.js');
const mongoose = require('mongoose');
mongoose.connect("mongodb://127.0.0.1:27017/todoListDB").then(() => console.log('connected')).catch(e => console.log(e))


const app = express();
app.set('view engine', 'ejs');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static("public"));


const itemSchema = mongoose.Schema({
    name: {
        type: String,
        required: true,
    }
});
const Item = new mongoose.model('Item', itemSchema);

// Item.insertMany([
//     { name: "Welcome to your Todo List" },
//     { name: "Hit '+' button to add a new item" },
//     { name: "<--Hit this to check" },
// ]);

const workItems = [];

app.get("/", (req, res) => {
    const day = date.getDate();
    Item.find({}).then(foundItems => {
        if (foundItems.length === 0) {
            Item.insertMany([
                { name: "Welcome to your Todo List" },
                { name: "Hit '+' button to add a new item" },
                { name: "<--Hit this to check" },
            ]);
            res.redirect("/")
        } else {
            res.render("list", { listTitle: day, newListItems: foundItems });
        }
    })
});

app.post("/", (req, res) => {
    if ((x = req.body.newItem) !== "") {
        if (req.body.list === 'Work List') {
            workItems.push(x);
            res.redirect("/work");
        } else {
            newListItems.push(x);
            res.redirect("/");
        }
    } else {
        res.redirect("/");
    }
});

app.get("/work", (req, res) => {
    res.render("list", { listTitle: "Work List", newListItems: workItems });
});

app.post("/work", (req, res) => {
    res.redirect("/work");
});

app.get("/about", (req, res) => {
    res.render("about", { listTitle: "About Me" });
});

app.listen(3000, () => {
    console.log("Server running on http://127.0.0.1:3000");
});

I expect it to only insert data one time if the database is empty. When I reload my page it should give me this:- expected result

Instead I am getting this:- unexpected result


Solution

  • Your Item.insertMany should be an asynchronous task. You need to either await it (also need to use async) or use a then block. Since you are already using then blocks in your code you could just refactor like so:

    Item.insertMany([
       { name: "Welcome to your Todo List" },
       { name: "Hit '+' button to add a new item" },
       { name: "<--Hit this to check" },
    ]).then((result) =>{
        res.redirect("/");
    }).catch((error) =>{
       console.log(error);
    });