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

Cha*_*har 1 javascript ruby-on-rails mongoose mongodb node.js

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

我是一名 Rails 开发人员,rails 框架有一种很好的方法来在 中播种数据seeds.rb,我希望在我的 Node.js 应用程序中实现同样的目标。

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

Yil*_*maz 7

首先在 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;
Run Code Online (Sandbox Code Playgroud)

然后创建一个 Seeder 文件夹 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();
    }
  });
});
Run Code Online (Sandbox Code Playgroud)

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

node seedProducts.js
Run Code Online (Sandbox Code Playgroud)