Appearance
mongoose-mpath
简介
mongoose-mpath是一个 mongoose 的插件, 用于实现 mongoose 的 树形结构数据
注意事项
- 使用此插件会在模型中添加
path,parent,level字段,用于存储路径信息
安装
bash
npm install mongoose-mpath --save示例
- 模型注册插件
javascript
const {Schema,model} = require('mongoose')
const mpath = require('mongoose-mpath')
const schema = new Schema({
name: String
})
const options={
modelName: 'Category', //模型名称
pathSeparator: '#', //路径分隔符 id1#id2#id3
onDelete: 'DELETE', //删除时的操作 DELETE(删除子集)、REPARENT(重定义父对象)
idType: Schema.ObjectId, //id类型
}
schema.plugin(mpath,options)
module.exports = model('Category',schema)- 模型新增方法
获取子集树
javascript
//getChildrenTree() 获取子集树
const options={
filters: {name: 'test'}, //过滤条件
fields: 'name', //返回字段
options: {limit: 10}, //查询条件
populate: 'name', //关联查询
minLevel: 1, //最小层级
maxLevel: 3, //最大层级
rootDoc:dom, //根节点
}
Model.getChildrenTree(options) //返回所有树形结构
/**/
let doc=await Model.findById('id')
let children=await doc.getChildrenTree(options) //返回当前节点的树形结构- 模型新增方法
获取所有祖先
javascript
const user = require('./models/user')
//getAncestors() 获取所有祖先
let doc=await Model.findById('id')
let parents=await doc.getAncestors()- 模型新增方法
获取所有子集
javascript
//getAllChildren() 获取所有子集
let doc=await Model.findById('id')
let children=await doc.getAllChildren() //数组- 模型新增方法
获取所有子集
javascript
let doc=await Model.findById('id')
let children=await doc.getImmediateChildren()- 模型新增方法
获取所有父级
javascript
let doc=await Model.findById('id')
let parents=await doc.getParent() //返回所有父级