0

Each time I use node app.js to start the server a new copy of the same object is created in database . In my code below it creates the test blog as many number of times as the node app.js is used to start the server .How can I fix this ?

var express    = require("express"),
    mongoose   = require("mongoose"),
    bodyParser = require("body-parser"),
    app        = express();

mongoose.connect('mongodb://localhost:27017/blog_app', {useNewUrlParser: true, useUnifiedTopology: true});
app.set("view engine", "ejs");
app.use(express.static("public"));
app.use(bodyParser.urlencoded({extended: true}));

var blogSchema = new mongoose.Schema({
    title: String,
    image: String,
    body: String,
    date: {
        type: Date,
        default: Date.now
    }
});

var Blog = mongoose.model("Blog", blogSchema);

Blog.create({
    title: "Test Blog",
    image: "https://images.unsplash.com/photo-1494256997604-768d1f608cac?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=2202&q=80",
    body: "This is a test app."
});


// INDEX route
app.get("/", function(req, res){
        res.redirect("/blogs");
});
app.get("/blogs", function(req, res){
        // res.render("index");
        Blog.find({}, function(err, blogs){
            if(err){
                console.log("ERROR!");
            } else {
                res.render("index", {blogs: blogs});
            }
        })
});



app.listen(3000, function(){
    console.log("SERVER HAS STARTED!");
});

use blog_app switched to db blog_app db.blogs.find() { "_id" : ObjectId("5dc2a990cebaeb07d43653ac"), "title" : "Test Blog", "image" : "https://unsplash.com/photos/-GzyUGKhjBY", "body" : "This is a test app.", "date" : ISODate("2019-11-06T11:08:00.162Z"), "__v" : 0 } { "_id" : ObjectId("5dc2aad48d1865088eed3881"), "title" : "Test Blog", "image" : "https://unsplash.com/photos/-GzyUGKhjBY", "body" : "This is a test app.", "date" : ISODate("2019-11-06T11:13:24.344Z"), "__v" : 0 } { "_id" : ObjectId("5dc2ae3f1f12100a748fdbb6"), "title" : "Test Blog", "image" : "https://unsplash.com/photos/-GzyUGKhjBY", "body" : "This is a test app.", "date" : ISODate("2019-11-06T11:27:59.182Z"), "__v" : 0 } { "_id" : ObjectId("5dc2ced6dbd5e902487e3241"), "title" : "Test Blog", "image" : "https://unsplash.com/photos/-GzyUGKhjBY", "body" : "This is a test app.", "date" : ISODate("2019-11-06T13:47:02.818Z"), "__v" : 0 } { "_id" : ObjectId("5dc2cf09a3052102541f30a9"), "title" : "Test Blog", "image" : "https://images.unsplash.com/photo-1494256997604-768d1f608cac?ixlib= rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=2202&q=80", "body" : "This is a test app.", "date" : ISODate("2019-11-06T13:47:53.972Z"), " __v" : 0 }

1 Answer 1

0

That is because you have these lines in your code, it creates Test Blog on each application run:

Blog.create({
    title: "Test Blog",
    image: "https://images.unsplash.com/photo-1494256997604-768d1f608cac?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=2202&q=80",
    body: "This is a test app."
});

If you want to create Test Blog record exactly once you better use Model.findOneAndUpdate with options.upsert = true. It will find record and update it, or will create new one if record hasn't been found.

Blog.findOneAndUpdate({name: "Test Blog"}, {
    title: "Test Blog",
    image: "https://images.unsplash.com/photo-1494256997604-768d1f608cac?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=2202&q=80",
    body: "This is a test app."
}, {upsert: true});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.