Mongoose自引用模式不为所有子文档创建ObjectId

时间:2017-02-27 00:14:55

标签: node.js mongodb mongoose mongoose-schema

我在mongoose中有一个Schema,它有一个自引用字段,如下所示:

var mongoose = require('mongoose');

var CollectPointSchema = new mongoose.Schema({
  name: {type: String},
  collectPoints: [ this ]
});

插入CollectPoint对象时:

{
  "name": "Level 1"
}

没关系,结果就像预期的那样:

{
  "_id": "58b36c83b7134680367b2547",
  "name": "Level 1",
  "collectPoints": []
}

但是当我插入自引用的子文档时,

{
  "name": "Level 1",
  "collectPoints": [{
    "name": "Level 1.1"
  }]
}

它给了我这个:

{
  "_id": "58b36c83b7134680367b2547",
  "name": "Level 1",
  "collectPoints": [{
    "name": "Level 1.1"
  }]
}

孩子_id的{​​{1}}在哪里?我需要这个CollectPointSchema

1 个答案:

答案 0 :(得分:1)

在声明嵌入的CollectPoint项时,您应该构建一个新对象:

var data = new CollectPoint({
    name: "Level 1",
    collectPoints: [
        new CollectPoint({
            name: "Level 1.1",
            collectPoints: []
        })
    ]
});

这样_idcollectPoints将由CollectPoint的实例创建,否则,您只是创建一个普通的JSONObject。

要避免出现这类问题,请为您的数组构建validator,如果其项目类型错误,将触发错误:

var CollectPointSchema = new mongoose.Schema({
    name: { type: String },
    collectPoints: {
        type: [this],
        validate: {
            validator: function(v) {
                if (!Array.isArray(v)) return false
                for (var i = 0; i < v.length; i++) {
                    if (!(v[i] instanceof CollectPoint)) {
                        return false;
                    }
                }
                return true;
            },
            message: 'bad collect point format'
        }
    }
});

这样会导致错误:

var data = new CollectPoint({
    name: "Level 1",
    collectPoints: [{
        name: "Level 1.1",
        collectPoints: []
    }]
});