你为什么不使用这样的东西。
//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 文件。但这就是我为我的项目所做的。