如何在mongoose集合中正确初始化文档

igo*_*uad 5 mongoose mongodb express mean-stack

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

我有一个带有字段"类别"的博客文章模型.我希望用户能够键入类别(使用typeahead),如果类别不存在,则用户可以创建它.但是,为了防止无组织的条目,我想用一个类别列表填充字段"category".

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

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

ma0*_*a08 5

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

//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'}]
})
Run Code Online (Sandbox Code Playgroud)

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

要初始化类别,可以通过解析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'
     ...
    }
    ...
]
Run Code Online (Sandbox Code Playgroud)

从文件中读取数据

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

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