两级嵌套的mongoose模式

时间:2014-05-06 10:30:36

标签: node.js mongodb mongoose schema

我希望能够在mongoose中创建以下结构

{
    "clientId": 9,
    "uniqueNodeId": "REFRESH:NODE:123123123_9_231",
    "parent": null,
    "status": "ACTIVE",
    "templates": [
        {
            "name": "temp",
            "body": "temp",
            "url": "temp",
            "imageUrl": "temp",
            "title": "temp",
            "personaId": 123,
            "status": "ACTIVE",
            "uniqueTemplateId": "REFRESH:TEMPLATE:123123123_9_231"
        }
    ]
}

templates是一个数组和json对象。这样做的正确方法是什么? 我尝试了以下代码。

var folderSchema = mongoose.Schema({
    "clientId": {type: Number, required: true},
    "uniqueNodeId": {type: String, required: true},
    "parent": {type: String, required: true},
    "status": {type: String, required: true},
    "templates": [{
        "name": {type: String, required: true},
        "body": {type: String, required: true},
        "url": {type: String, required: true},
        "imageUrl": {type: String, required: true},
        "title": {type: String, required: true},
        "personaId": {type: String, required: true},
        "status": {type: String, required: true},
        "uniqueTemplateId": {type: String, required: true}
    }]
});

但是我收到以下错误:

TypeError: Undefined type at `paths.clientId`
  Did you try nesting Schemas? You can only nest using refs or arrays.

这是什么意思以及如何纠正它?

1 个答案:

答案 0 :(得分:0)

您定义它的更好方法是将模式定义分开:

var Schema = mongoose.Schema;

var templateSchema = new Schema({
    "name": {type: String, required: true},
    "body": {type: String, required: true},
    "url": {type: String, required: true},
    "imageUrl": {type: String, required: true},
    "title": {type: String, required: true},
    "personaId": {type: String, required: true},
    "status": {type: String, required: true},
    "uniqueTemplateId": {type: String, required: true}
},{ _id: false});


var folderSchema = new Schema({
    "clientId": {type: Number, required: true},
    "uniqueNodeId": {type: String, required: true},
    "parent": {type: String},
    "status": {type: String, required: true},
    "templates": [ templateSchema ]
});

var Folder = mongoose.model( "Folder", folderSchema );

_id: false部分是可选的,是一种告诉mongoose不会在数组内的条目上自动生成_id字段的方法。这是默认设置,因此无论您是否想要这个,都取决于您。

如果您改变主意并希望拥有引用的模型而不是嵌入式模式,这也可以实现清晰的分离。如果您想在其他地方重新使用组件,这也是值得的。

所以在最低使用率上:

Folder.findOne({},function(err,doc) {
  if (err) {
    console.log(err);
    return;
  }

  console.log(doc);

});

根据标准的Mongoose命名

,使用名为folders的数据集合

产地:

{ _id: 5368c2267ea39d89989df13c,
  clientId: 9,
  uniqueNodeId: 'REFRESH:NODE:123123123_9_231',
  parent: null,
  status: 'ACTIVE',
  templates:
   [ { name: 'temp',
       body: 'temp',
       url: 'temp',
       imageUrl: 'temp',
       title: 'temp',
       personaId: '123',
       status: 'ACTIVE',
       uniqueTemplateId: 'REFRESH:TEMPLATE:123123123_9_231' } ] }