如何在MongoDB中recursion地遍历嵌套的文档
我试图遍历MongoDB模型中的第n个节点。 这是我的用户模型。
用户模型
var UserSchema = new Schema({ firstname : { type: String}, parents:[{type: mongoose.Schema.Types.ObjectId, ref: 'User' }], children:[{type: mongoose.Schema.Types.ObjectId, ref: 'User' }], partner:[{type: mongoose.Schema.Types.ObjectId, ref: 'User' }], sibling:[{type: mongoose.Schema.Types.ObjectId, ref: 'User' }], });
我不知道如何从这个模型中生成一个类似于结构的树,关于如何实现这个的任何想法?,我使用Mongoose作为模型,并且尝试了深层树和填充没有成功,因为它只适用于第一级。
提前致谢。
最简单的方法就是使用蓝鸟承诺,具体来说就是each
, props
, reduce
和map
方法,这取决于你的使用情况。
在你的情况下,我会build议一些沿线的东西
var bluebird = require('bluebird'); var mongoose = require('mongoose'); var UserModel = mongoose.model('User'); function getUser(userId) { return UserModel.findOne({_id: userId}).lean().exec() .then(function(user){ return bluebird.props({ firstName: user.firstName, parents: bluebird.map(user.parents, getUser), children: bluebird.map(user.children, getUser), partner: bluebird.map(user.partner, getUser), sibling: bluebird.map(user.sibling, getUser) }) }); } // Then call getUser once on the root node, eg getUser(rootUserObjectId) .then(function(userTree){ console.log(userTree) })
让我知道这是怎么回事!