我在猫鼬中有一个具有自引用字段的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"
  }]
}


_idCollectPointSchema在哪里?我需要这个_id

最佳答案

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

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


这样,将通过_id实例化创建collectPointsCollectPoint,否则,您只是在创建普通的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: []
    }]
});

10-02 20:00