【问题标题】:What is the best way to seed data in nodejs mongoose在nodejs mongoose中播种数据的最佳方法是什么
【发布时间】:2017-06-08 05:48:31
【问题描述】:

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

我是一名 Rails 开发人员,Rails 框架有一种很好的方法可以在 seeds.rb 中播种数据,我想在我的 node.js 应用程序中实现同样的功能。

由于我是 node.js 的新手,我对网络上不同的可用资源感到困惑。

【问题讨论】:

  • 你到底在困惑什么?你有没有尝试过?
  • Node/express 不像 rails 那样固执己见,也不遵循惯例。因此,只需添加一个带有创建代码的 seed.js 和 module.export 它。将if(seedDB){require(seed.js)()} 放在您的主服务器/索引文件中。 seedDB 是开启和关闭种子的标志。

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


【解决方案1】:

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

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;

然后创建一个种子文件夹 播种机/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

【讨论】:

  • 谢谢队友@Yilmaz!
【解决方案2】:

您可以使用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;

【讨论】:

    猜你喜欢
    • 2010-10-20
    • 2018-06-07
    • 2016-07-01
    • 2020-06-27
    • 2023-01-15
    • 1970-01-01
    • 1970-01-01
    • 2021-04-22
    • 1970-01-01
    相关资源
    最近更新 更多