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

时间:2014-08-02 03:48:24

标签: mongodb express mongoose mean-stack

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

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

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

现在,如果我将它与子文档一起使用,我怎样才能初始化模型"类别"有关服务器启动的类别列表?

2 个答案:

答案 0 :(得分:3)

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

//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文件。但这就是我为我的项目所做的。

答案 1 :(得分:0)

在我的情况下,而不是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();
}});
相关问题