在nodejs mongoose中播种数据的最佳方法是什么

时间:2017-06-08 05:48:31

标签: ruby-on-rails node.js mongoose

在我的应用程序中,我需要将数据播种到数据库中,最好的方法是什么,我应该在哪里编写用于播种数据的代码,应该是什么文件夹结构。

我是rails开发人员,rails框架有一种很好的方法可以在seeds.rb中播种数据,我希望在我的nodejs应用程序中实现相同的功能。

由于我是nodejs的新手,因此我对网络上可用的不同资源感到困惑。

2 个答案:

答案 0 :(得分:0)

您可以使用mongoose-data-seed包来处理这项工作。

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

使用mongoose-data-seed,您基本上可以创建看起来像这样的播种器文件:

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

const data = [{
  email: 'user1@gmail.com',
  password: '123123', password_confirmation: '123123',
  isAdmin: true
}, {
  email: 'user2@gmail.com',
  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;

答案 1 :(得分:0)

首先在models文件夹中创建模型。

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;

然后创建一个种子文件夹 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.com/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();
    }
  });
});

最后,您只能在终端上运行一次seedProducts.js

node seedProducts.js