如何在MongoDB中将嵌套对象显示为超级对象?

时间:2018-08-01 16:53:11

标签: javascript node.js mongoose mongoose-populate

here所述,我不得不将引用对象保存在称为“ item”的嵌套键中;

var userSchema = new Schema({
  name: String,
  connections: [{
    kind: String,
    item: { type: ObjectId, refPath: 'connections.kind' }
  }]
});

var organizationSchema = new Schema({ name: String, kind: String });

var User = mongoose.model('User', userSchema);
var Organization = mongoose.model('Organization', organizationSchema);

在我的数据库中,它更像是这样:

var childSchema = new Schema({
    kind: String,
    item: {
        type: Schema.Types.ObjectId,
        refPath: 'children.kind'
    }
},{ _id : false, strict:false });

var schema = new Schema({
    name: String,
    kind: String,
    children: [childSchema]
},{
    strict: false
});

现在,它是一个基于树的文件夹结构模型,它可以将Folder或Leaf作为子对象。

我需要一个递归填充,所以我找到了答案,就变成了这样;

var autoPopulateChildren = function(next) {
    this.populate({path:'children.item', select:'name id children'});
    next();
};

schema.pre('findOne', autoPopulateChildren)
    .pre('find', autoPopulateChildren)

现在,当我进行find查询时,会得到类似这样的示例;

{
  "name": "Some Folder",
  "children": [
    {
      "kind": "Leaf",
      "item": {
        "name": "First Level Leaf",
        "id": "5b61c85f25375fddf6048d3c"
      }
    },
    {
      "kind": "Folder",
      "item": {
        "name": "First Level Folder",
        "id": "5b61d844d77fb30b9537e5d1"
        "children": [
          {
            "kind": "Leaf",
            "item": {
              "name": "Second Level Leaf",
              "id": "5b61c85f25375fddf6048d3c"
            }
          }
        ]
      }
    }
  ],
  "id": "5b61c85f25375fddf6048d3d"
}

但是现在,我需要摆脱“种类”(不显示),并且还需要将“ item”对象显示为儿童(应该是name而不是item:{name:'a'}

{
  "name": "Some Folder",
  "children": [
    {
      "name": "First Level Leaf",
      "id": "5b61c85f25375fddf6048d3c"
    },
    {
      "name": "First Level Folder",
      "id": "5b61d844d77fb30b9537e5d1"
      "children": [
        {
          "name": "Second Level Leaf",
          "id": "5b61c85f25375fddf6048d3c"
        }
      ]
    }
  ],
  "id": "5b61c85f25375fddf6048d3d"
}

如何在autoPopulateChildren函数上执行此操作?

0 个答案:

没有答案