Mongoose的虚拟人口问题

时间:2017-06-14 13:25:09

标签: node.js mongoose

我正在使用带有node.js的mongo DB,并且所有模型都在公共文件夹中并使用虚拟填充来在模型之间进行通信。例如model1-> model2-> model3(model1具有model2和model2的依赖关系model3的依赖关系。

以下是代码:

//module Schema
var moduleSchema = new Schema(
  {
      moduleCode: { type: String, required: true, unique: true},
      moduleName: { type: String, required: true },
      description: String,
      **categoryId: { type: Schema.Types.ObjectId, required: true },**
      active: Boolean,
      createdDate: { type: Date, default: Date.now},
      lastUpdatedDate: { type: Date, default: Date.now}
  },
  { 
      toJSON: { virtuals: true }, 
      toObject: {virtuals: true}
  }
);

moduleSchema.virtual('categoryData', {
  ref: 'Category', 
  localField: 'categoryId',
  foreignField: '_id',
  justOne: true
});

第二模特:

{
                "_id": "59410a5dab85113a7cdc0507",
                "packageGroupCode": "P02",
                "packageGroupName": "package2",
                "description": "package2",
                "moduleId": "5940efeadb8fe72a8cb4e056",
                "active": true,
                "__v": 0,
                "lastUpdatedDate": "2017-06-14T11:30:43.798Z",
                "createdDate": "2017-06-14T11:30:43.798Z",
                "moduleData": {
                    "_id": "5940efeadb8fe72a8cb4e056",
                    "moduleName": "module name",     
                     **"categoryData": null,**
                **"id": "5940efeadb8fe72a8cb4e056"**
            },
            **"id": "59410a5dab85113a7cdc0507"**
        }

如果我正在为第一个模型运行api,那么我正在将第二个模型中的dependencris(category)数据进行竞争。

以下是我得到的结果:

{
                "_id": "59410a5dab85113a7cdc0507",
                "packageGroupCode": "P02",
                "packageGroupName": "package2",
                "description": "package2",
                "moduleId": "5940efeadb8fe72a8cb4e056",
                "active": true,
                "__v": 0,
                "lastUpdatedDate": "2017-06-14T11:30:43.798Z",
                "createdDate": "2017-06-14T11:30:43.798Z",
                "moduleData": {
                    "_id": "5940efeadb8fe72a8cb4e056",
                    "moduleName": "module name"
                }
            }

有人可以告诉我我要做什么来忽略 moduleDate 中的 catergoryData 和ID重复。

Expexted JSON应该是这样的:

Connection.Open()

1 个答案:

答案 0 :(得分:0)

如果你的结果存储在“theObject”中,你可以删除这样的键:

delete theObject["id"];
delete theObject["moduleData"]["id"];
delete theObject["moduleData"]["categoryData"];