node.js - Mongoose 自引用架构不为所有子文档创建 ObjectId

标签 node.js mongodb mongoose mongoose-schema

我在 Mongoose 中有一个架构,它有一个自引用字段,如下所示:

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"
  }]
}

CollectPointSchema_id 在哪里?我需要这个_id

最佳答案

在声明嵌入的 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: []
    }]
});

关于node.js - Mongoose 自引用架构不为所有子文档创建 ObjectId,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42475905/

相关文章:

node.js - FacebookGraphAPIError : (#100) Tried accessing nonexisting field (user_photos) on node type (User)

mongodb - $regex 与 $concat 在 MongoDB 的查询中

node.js - Nestjs: Mongoose 中子文档数组的正确模式(没有默认 _id 或重新定义 ObjectId)

javascript - 处理API调用中丢失的数据

javascript - 使用socket.io的聊天服务器,消息未附加到列表中

javascript - 在javascript中一个接一个地运行一个函数

javascript - 铁路由器: Meteor JS

MongoDB 错误 : moveChunk failed to engage TO-shard in the data transfer: cannot start recv'ing chunk

node.js - Heroku 服务器上 NodeJS 应用程序中 MissingSchemaError

node.js - 使用 Mongoose 进行架构投票的 "right way"?