首页 文章

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

提问于
浏览
4

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

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

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

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

1 回答

  • 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 时,检查 Category 集合中是否已存在 categories . 这将很快,因为我们使用类别名称( _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文件 . 但这就是我为我的项目所做的 .

相关问题