最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - What is the best way to seed data in nodejs mongoose - Stack Overflow

programmeradmin3浏览0评论

I need to seed data into the database in my application. What is the best way to do that? Where should I write the code for seeding the data? what should be the folder structure for this?

I am a rails developer and rails framework has a nice way of seeding the data in seeds.rb, and I want to achieve the same thing in my node.js application.

Since I am new to node.js, I am confused between different available resources on the web.

I need to seed data into the database in my application. What is the best way to do that? Where should I write the code for seeding the data? what should be the folder structure for this?

I am a rails developer and rails framework has a nice way of seeding the data in seeds.rb, and I want to achieve the same thing in my node.js application.

Since I am new to node.js, I am confused between different available resources on the web.

Share Improve this question edited Oct 16, 2021 at 22:04 Yilmaz 49.5k18 gold badges215 silver badges268 bronze badges asked Jun 8, 2017 at 5:48 chandradot99chandradot99 3,8666 gold badges28 silver badges46 bronze badges 2
  • What is exactly you confused? Have you tried something? – Roman Kiselenko Commented Jun 8, 2017 at 5:52
  • Node/express is not opinionated like rails and does not follow a convention. So, simply add a seed.js with a create code and module.export it. Place if(seedDB){require(seed.js)()} in your main server/index file. seedDB is a flag to switch on and off the seed. – Talha Awan Commented Jun 8, 2017 at 5:55
Add a ment  | 

3 Answers 3

Reset to default 7

First create your model in models folder.

models/product.js
const mongoose = require("mongoose");
const productSchema = new mongoose.Schema({
  image: { type: String, required: true },
  title: { type: String, required: true },
  author: { type: String, required: true },
  description: { type: String, required: true },
  price: { type: Number, required: true }
});
const Product = mongoose.model("Product", productSchema);
module.exports = Product;

Then create a seeder folder seeder/seedProducts.js

const Product = require("../models/product");
const mongoose = require("mongoose");
const dev = require("../config/dev"); //get your mongoose string
//create your array. i inserted only 1 object here
const products = [   
  new Product({
    image:
      "https://static.seattletimes./wp-content/uploads/2018/01/a8e801dc-f665-11e7-bf8f-ddd02ba4a187-780x1181.jpg",
    title: "Origin",
    author: "Dan Brown",
    description:
      "2017 mystery thriller novel. Dan Brown is back with another thriller so moronic you can feel your IQ points flaking away like dandruff",
    price: 12
  }),]
//connect mongoose
mongoose
  .connect(String(dev.db), { useNewUrlParser: true })
  .catch(err => {
    console.log(err.stack);
    process.exit(1);
  })
  .then(() => {
    console.log("connected to db in development environment");
  });
//save your data. this is an async operation
//after you make sure you seeded all the products, disconnect automatically
products.map(async (p, index) => {
  await p.save((err, result) => {
    if (index === products.length - 1) {
      console.log("DONE!");
      mongoose.disconnect();
    }
  });
});

Finally you will run seedProducts.js on the terminal only once.

node seedProducts.js

You can use the mongoose-data-seed package to handle this job.

https://github./sharvit/mongoose-data-seed

With mongoose-data-seed you are basically creating seeders files that look like that:

import { Seeder } from 'mongoose-data-seed';
import { User } from '../server/models';

const data = [{
  email: '[email protected]',
  password: '123123', password_confirmation: '123123',
  isAdmin: true
}, {
  email: '[email protected]',
  password: '123123', password_confirmation: '123123',
  isAdmin: false
}];

class UsersSeeder extends Seeder {

  async shouldRun() {
    const usersCount =  await User.count().exec();

    return usersCount === 0;
  }

  async run() {
    return User.create(data);
  }
}

export default UsersSeeder;

Drop collection first (if you want):

const productSchema = require("../models/product-schema")

productSchema.collection.drop()
  .then(() => console.log("Drop"))
  .catch((err) => console.error(err))

Seed data from JSON (Array of Objects):

const productJSON = require("./product-data-seed")

productSchema.insertMany(productJSON)
  .then(() => console.log("Done"))
  .catch((err) => console.error(err))
发布评论

评论列表(0)

  1. 暂无评论