Reputation: 3512
I'm a bit new to the concept of seeding.
My goal is to have a set of data in the database that can be shown on the front end. I don't want to "Seed" the database each time I start the server. I simply want to add one set of data. I've figured out how to seed the database but only if I seed it each time I start the server. Am I going about this correctly? How do I only seed it once? Thanks! I run the seedfoods()
function in app.js when the server starts.
var mongoose = require("mongoose");
var Food = require("./models/food");
function seedfoods() {
//add the foods to the database
data.forEach(function(seedfoods){
Food.create(seedfoods, function(err, Food){
if(err){
console.log(err)
} else {
console.log("added a food");
}
});
});
}
var data = [
{
name: "Avocados",
easyFood: true,
phase1: true,
about: "Yum Avocados",
},
{
name: "Milk",
easyFood: true,
phase1: true,
about: "Yum Milk",
},
]
module.exports = seedfoods;
Upvotes: 1
Views: 1490
Reputation: 1612
A couple of options:
Have an initial script on the start of the server which runs the seed once and stores some sort of record of doing so (e.g. a db entry or a file or something similiar). This is probably the cleanest, but also the one with the biggest effort.
What I suggest you do is this: You can skip the detection of existing documents by simply using the upsert option in an update query, which will only create a new document, if it doesn't exist already. So just run your seed on every start with an update operation with the option {upsert: true}
.
https://mongoosejs.com/docs/api.html#model_Model.findOneAndUpdate
Upvotes: 2