在MongoDB中使用Mongoose创build关系(在Node.js中)

我试图在没有任何运气的情况下在Stackoverflow上find任何类似的问题。 我正在努力寻找创build两个文件之间关系的正确方法。 这是一个非常简单的分层分类案例。 每个类别可以有一个父母和多个孩子。

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); 

当我创build一个新的类别时,我得到_id给(如果有的话)它应该有的父类。 我得到这个_id作为从POST / PUT请求的string,并使用这个_id获取类别。 取得工作正常,我得到正确的类别作为结果。 但是,这是我奋斗的地方,我如何使用mongoose查询返回的结果来创build新的类别和它的父之间的关系?

 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:{name:'父类别',_id:5218dcd6e6887dae40000002} .. parentCategory._id:undefined

我已经尝试以多种不同的方式设置父属性,我不能得到它的工作。 没有任何运气find关于这个问题的文件。

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

 //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....); } 

还要注意,如果你有一个模式,并且你指定了一些与模式不匹配的东西,那么mongoose会丢掉数据,这可能是你正在发生的事情,假设你在某个时候调用了category.save()