MongooseError:强制转换为嵌入式失败

时间:2017-04-11 21:11:01

标签: node.js mongodb mongoose

我正在创建一个mongoose Schema,但我得到了MongooseError

这是我的方案:

let RestaurantSchema = new Schema({
    ratings: {
        type: [{
            id: Number,
            value: Number,
            _id: false
        }],
        default: [
            { id: 1, value: 0 },
            { id: 2, value: 0 },
            { id: 3, value: 0 },
            { id: 4, value: 0 },
            { id: 5, value: 0 }
        ]
    },
    menu: [{
        ratings: {
            type: [{
                id: Number,
                value: Number,
                _id: false
            }],
            default: [
                { id: 1, value: 0 },
                { id: 2, value: 0 },
                { id: 3, value: 0 },
                { id: 4, value: 0 },
                { id: 5, value: 0 }
            ]
        }
    }]
})

这就是我得到的错误:

/var/app/node_modules/mongoose/lib/schema/documentarray.js:322
             throw new CastError('embedded', valueInErrorMessage,
             ^
 MongooseError: Cast to embedded failed for value "{ id: 5, value: 0 }" at path "rating"
     at CastError (/var/app/node_modules/mongoose/lib/error/cast.js:26:11)
     at DocumentArray.cast (/var/app/node_modules/mongoose/lib/schema/documentarray.js:322:19)
     at DocumentArray.SchemaType.getDefault (/var/app/node_modules/mongoose/lib/schematype.js:616:23)
     at EmbeddedDocument.Document.$__buildDoc (/var/app/node_modules/mongoose/lib/document.js:265:22)
     at EmbeddedDocument.Document (/var/app/node_modules/mongoose/lib/document.js:61:20)
     at EmbeddedDocument [as constructor] (/var/app/node_modules/mongoose/lib/types/embedded.js:31:12)
     at new EmbeddedDocument (/var/app/node_modules/mongoose/lib/schema/documentarray.js:70:17)
     at DocumentArray.SchemaArray [as constructor] (/var/app/node_modules/mongoose/lib/schema/array.js:67:21)
     at new DocumentArray (/var/app/node_modules/mongoose/lib/schema/documentarray.js:31:13)
     at Function.Schema.interpretAsType (/var/app/node_modules/mongoose/lib/schema.js:643:16)
     at Schema.path (/var/app/node_modules/mongoose/lib/schema.js:563:29)
     at Schema.add (/var/app/node_modules/mongoose/lib/schema.js:445:12)
     at new Schema (/var/app/node_modules/mongoose/lib/schema.js:99:10)
     at Object.<anonymous> (/var/app/models/restaurant.js:12:24)
     at Module._compile (module.js:571:32)
     at Object.Module._extensions..js (module.js:580:10)
     at Module.load (module.js:488:32)
     at tryModuleLoad (module.js:447:12)
     at Function.Module._load (module.js:439:3)
     at Module.require (module.js:498:17)
     at require (internal/module.js:20:19)
     at Object.<anonymous> (/var/app/controllers/restaurant.js:6:18)
     at Module._compile (module.js:571:32)
     at Object.Module._extensions..js (module.js:580:10)
     at Module.load (module.js:488:32)
     at tryModuleLoad (module.js:447:12)
     at Function.Module._load (module.js:439:3)
     at Module.require (module.js:498:17) 

我做错了什么?

4 个答案:

答案 0 :(得分:1)

这似乎是v4.9.4中mongoose中的错误。实际上还有另一个错误产生这个。当您使用type作为对象{id: Number,value: Number,_id: false}而不是数组时,会出现后者:

TypeError: this.__parentArray._markModified is not a function
    at EmbeddedDocument.markModified (/home/user/Desktop/node_modules/mongoose/lib/types/embedded.js:87:24)
    at SingleNested.Subdocument.markModified (/home/user/Desktop/node_modules/mongoose/lib/types/subdocument.js:62:18)
    at SingleNested.Document.$__set (/home/user/Desktop/node_modules/mongoose/lib/document.js:874:10)

这是引用here的引用错误。它似乎已经修复了一段时间但已经重新浮出水面。我已经开了一个关于这个here的新问题。

解决方法与所述here相同,替换为node_modules/mongoose/lib/types/embedded.js

EmbeddedDocument.prototype.markModified = function(path) {
  this.$__.activePaths.modify(path);
  if (!this.__parentArray) {
    return;
  }

EmbeddedDocument.prototype.markModified = function(path) {
  this.$__.activePaths.modify(path);
  if (!this.__parentArray || !this.__parentArray._markModified) {
    return;
  }

此外,将模型重新构建为不同的模式有助于调试问题:

let RatingsItemSchema = new mongoose.Schema({
    id: Number,
    value: Number,
    _id: false
});

let RatingsItem = db.model('RatingsItem', RatingsItemSchema);

let RatingsSchema = new mongoose.Schema({
    ratings: {
        type: [RatingsItemSchema],
        default: [
            { id: 1, value: 0 },
            { id: 2, value: 0 },
            { id: 3, value: 0 },
            { id: 4, value: 0 },
            { id: 5, value: 0 }
        ]
    },
    _id: false
});

let RestaurantSchema = new mongoose.Schema({
    ratings: {
        type: [RatingsItemSchema],
        default: [
            { id: 1, value: 0 },
            { id: 2, value: 0 },
            { id: 3, value: 0 },
            { id: 4, value: 0 },
            { id: 5, value: 0 }
        ]
    },
    menu: {
        type: [RatingsSchema]
    }
});

let Ratings = db.model('Ratings', RatingsSchema);
let Restaurant = db.model('Restaurant', RestaurantSchema);

let rest = new Restaurant();
rest.menu.push(new Ratings());
console.log(JSON.stringify(rest, null, 2));

答案 1 :(得分:0)

不一定与上面的情况有关,但是发生此错误的一种情况(发生在我身上)是在Schema需要一个对象,但是代码尝试保存到数组时。即,如果:

var MySubSchema = new Schema(
    {
        type: String,
        meta: String
    }
)

var MySchema = new Schema(
    subSchema: MySubSchema,
    otherSubSchema: OtherSubSchema 
)

但是用于保存数据的路由/控制器如下:

var mySchemaObj = new MySchema(
  {mySubSchema: [new MySubSchema(  //<-- Shouldn't have array "[" here
       {
          type: "foo",
          meta: "bar"
       }
    )]
  } 
)

. . . 
. . . 

mySchemaObj.save() . . . // <-- This will throw the "Cast to Embedded Failed" error, because MySchema expects a single MySubSchema Object, but the code above instantiates MySubSchema in an array. 

答案 2 :(得分:0)

这可能有点晚了,但对于和我一样面临同样问题的其他人来说。
假设说,我有一个这样的架构

const sampleSchema = new Schema({
   productId: Number
   productName: String
})

而且,这是我想存储在其中的数据。

{
   productId:"product_1000",
   productName: "sampleProduct"
}

现在,当我尝试将数据存储在其中时,我会收到 CastError: Cast to Embedded failed for value
你明白我的错误了吗?让我详细说明一下,在架构中,productId 是一个 数字 和我试图存储的数据< /strong> 是一个字符串。为了实现这一点,我们必须将 productId 的类型从 Number 更改为 String

因此,如果您收到转换错误,请再次检查架构。这是一个简单的错误,但我花了很多时间来找出问题所在。

答案 3 :(得分:0)

在我的情况下,req.body 与预定义的猫鼬模式不匹配,我试图保存一个 ObjectId 数组, req.body 是:

{
   cart: ["60d9b457a6c11f2a3818051a"]
}

但是猫鼬模式是

cart: [
   {
      product: {
         type: mongoose.Schema.Types.ObjectId,
         ref: 'products'
      }
   }
]

我像这样更改了猫鼬模式?以使其工作:

cart: [
   {
      type: mongoose.Schema.Types.ObjectId,
      ref: 'products'
   }
]