【问题标题】:How to properly initialize documents in mongoose collection如何正确初始化猫鼬集合中的文档
【发布时间】:2014-09-25 07:42:00
【问题描述】:

如果不推荐我的设计,请纠正我:

我有一个带有“类别”字段的博客文章模型。我希望用户能够输入类别(提前输入),如果类别不存在,用户将能够创建它。但是,为了防止杂乱无章的条目,我想用类别列表填充“类别”字段。

问题是,我应该将字段“category”用作数组还是引用另一个名为“Category”的模型的子文档?我假设后者将是推荐的设计,因为它避免了代码复制并简化了用户添加新类别所需的交互。

现在,如果我将它与子文档一起使用,我如何在服务器启动时使用类别列表初始化模型“类别”?

【问题讨论】:

    标签: mongodb express mongoose mean-stack


    【解决方案1】:

    在我的情况下,而不是 buildCategories - 我添加了架构方法,只需从 json 文件导入 initialData(不需要 fs.readFile)。

    Category.methods = {
    async setInitialData() {
        return this.collection.insertMany(initialData, err => {
            if (err){
                return console.error(err);
            }
            console.log("Initial documents inserted to Category Collection");
        });
    }}
    

    然后在控制器中:

    Category.findOne({}, async (err,doc) => {
    if(!doc){
        const category = new Category();
        await category.setInitialData();
    }});
    

    【讨论】:

      【解决方案2】:

      你为什么不使用这样的东西。

      //Category schema
      //Store all the categories available in this collection
      var categorySchema=new Schema({
           _id:String,//name of category
           description:String
           //other stuff goes here
      })
      mongoose.model(categorySchema, 'Category')
      
      //blog post schema
      var postSchema=new Schema({
          //all the relevant stuff
          categories:[{type:String,ref:'Category'}]
      })
      

      现在每当发布blog post 时,请检查给定的categories 是否已经存在于Category 集合中。这将很快,因为我们使用类别名称 (_id) 作为索引本身。因此,对于每个新类别,您都应该插入Category 集合,然后插入blog post。这样,如果需要,您可以 populate categories 数组。

      要初始化类别,可以通过解析更具可读性的JSON文件来完成。仅当我们使用空数据库(即删除 Categories 集合时)才应解析文件

      创建一个 Categories.json 文件。 Categories.json 的内容:

      [
          {
            _id:'Category1',//name of category
           description:'description1'
           ...
          },
          {
            _id:'Category2',//name of category
           description:'description2'
           ...
          },{
            _id:'Category3',//name of category
           description:'description3'
           ...
          }
          ...
      ]
      

      从文件中读取数据

      fs=require('fs');
      var buildCategories=fs.readFile(<path to Categories.json>,'utf8',function(err,data){          
      
          if (err) {
              //logger.error(err);
              return ;
          }
          var datafromfile=JSON.parse(data);
          data.forEach(function(obj){
             var catOb=new Category(obj)
             obj.save(function(err,doc){..});
          })
      });
      //To initialize when the Category collection is empty
      Category.findOne({},function(err,doc){
          if(!doc){
             //Collection is empty
             //build fomr file
             buildCategories();
          }
      });
      //Or you can just manually call the function whenever required when server starts
      buildCategories();
      

      您可能会争辩说您可以导入 csv 文件。但这就是我为我的项目所做的。

      【讨论】:

      • 谢谢你,@ma08。这几乎就是我正在做的事情,除了“postSchema”中的类别是针对单个条目而不是数组的事实。现在,我想知道的是,如何在向用户打开网站之前将一些类别添加到数据库中(我想要这个,因为用户会有预先输入的类别建议)。你认为我应该手动将它们添加到数据库中吗?我可以按照docs.mongohq.com/importing-exporting/from-csv.html 中的描述构建一个 CSV 并导入到 MongoHq。你怎么看?谢谢。
      • @igorauad 检查我的编辑。抱歉,错过了初始化部分。
      • 谢谢@ma08,这正是我所需要的。如果我有足够的声誉,我会投票。最好的问候
      猜你喜欢
      • 2021-05-19
      • 2017-09-11
      • 1970-01-01
      • 1970-01-01
      • 2019-05-22
      • 2017-04-28
      • 2014-12-21
      • 2021-02-06
      • 2020-08-14
      相关资源
      最近更新 更多