2013-08-24 94 views
2

我试图在没有任何运气的情况下在Stackoverflow上找到任何类似的问题。我正在努力寻找创建两个文档之间关系的正确方法。这是一个非常简单的分层分类案例。每个类别可以有一个父母和多个孩子。使用Mongoose在MongoDB中创建关系(在Node.js中)

var categorySchema = Schema({ 
    name: String, 
    parent: { type: Schema.ObjectId, ref: 'Category' }, 
    children: [{ type: Schema.ObjectId, ref: 'Category' }], 
    order: Number 
}); 

var Category = mongoose.model('Category', categorySchema); 

当我创建一个新的类别时,我得到了_id到(如果有的话)父级它应该有的。我将这个_id作为POST/PUT请求中的字符串并使用此_id获取类别。抓取工作正常,我得到正确的类别作为结果。但这是我奋斗的地方,我如何使用mongoose查询返回的结果来创建新类别与其父类之间的关系?

var query = Category.find({'_id': parentCategoryID}); 
query.select('name'); 
query.exec(function (err, parentCategory) { 
    if (!err) { 
     console.log("Fetched parentCategory: "+parentCategory+".. parentCategory._id: "+parentCategory._id); 
     var parent = parentCategory.toObject(); 
     var category = new Category(); 
     category.name = name; 
     category.parent = Schema.ObjectId(parent._id); 

的console.log 撷取的parentCategory:{名: '父类别',_id: 5218dcd6e6887dae40000002} .. parentCategory._id:未定义

我试图在多设置parent属性不同的方式,我不能得到它的工作。还没有找到关于这个问题的文件的运气。

非常感谢任何帮助,我希望更多的人能从这个问题的答案中受益。

+1

对于像Neo4j这样的图形数据库而言,这听起来更像是一个像MongoDB这样的面向文档数据库的工作。 – Philipp

+0

我真的不知道如何从我的问题中获得足够的信息来得出结论。类别部分只是实际数据模型的一小部分。然后,我还没有对MongoDB的优点/缺点进行广泛的研究,我选择了MongoDB来学习新的东西。感谢您的输入,但从未听说过Neo4j。 – oehman

回答

1
//problem 1: `find` returns a list of results. You just need findById 
var query = Category.findById(parentCategoryID); 
query.select('name'); 
query.exec(function (err, parentCategory) { 
    //Problem 2: don't ignore errors. Handle them first and short-circuit return 
    if (err) { 
     console.err(err); 
     return; 
    } 
    console.log("Fetched parentCategory: "+parentCategory+".. parentCategory._id: "+parentCategory._id); 
    //problem 3: mongoose will do the right thing with your schema here 
    //all you need is 
    var category = new Category(); 
    category.name = name; 
    category.parent = parentCategory; 
    //and don't forget 
    category.save(...callback....); 
} 

另外请注意,如果你有一个模式,你指定的东西,不模式匹配,猫鼬将只是下降的数据,这可能是发生了什么事给你,假设你在某些时候叫category.save()

+0

我删除了错误处理,并保存为了不膨胀我的问题的关键部分。显然这些都存在。 你说得对,上面的代码有效。我想我没有测试这种方式来修复我的模式后分配parentCategory。 谢谢! – oehman

+0

不要忘记处理parentCategory为空。 –