在尝试保存包含模型的模型时,Mongoose,CastError:Cast to Array的值失败。

时间:2015-10-28 04:57:37

标签: node.js mongodb mongoose nosql

我正在尝试使用mongoose为我的mongodb数据库创建模型。这就是我想要做的事情:

var Class = mongoose.model('Class', {className: String, marks: [{type: Number}], grades: [{type: Number}]});
var User = mongoose.model('User', {email: String, classes: [Class] });


//Lets create a new user
var class1 = new Class({className: 'aaa', marks: [72, 88, 63], grades: [30, 40, 30]});
var user1 = new User({email: 'aaa@some.com', classes: [class1]});

保存class1似乎没问题,但是当我查看mongodb时,会显示:{ "_id" : ObjectId("someId"), "className" : "TEST1234", "grades" : [ 30, 40, 30 ], "marks" : [ 72, 88, 63 ], "__v" : 0 }

什么是"__v : 0"

保存用户根本不成功,这是以下错误:ValidationError: CastError: Cast to Array failed for value "{ marks: [ 72, 88, 63 ], grades: [ 30, 40, 30 ], _id: someId, className: 'TEST1234' }" at path "classes"

错误究竟是什么意思?为什么要向阵列投射任何东西?不应该classes: [Class]class类型的数组吗?

7 个答案:

答案 0 :(得分:73)

伙计,我有类似的问题创建这样的架构:

QuestionnaireSchema = mongoose.Schema({
    formId: Number,
    name: String,
    questions: [
        {
            type: String,
            title: String,
            alternatives:[{
                label: String,
                value: "Mixed"
            }]
        }
    ]
});

我的错误是我正在使用"输入"作为字段名称,这是mongoose中的保留字。

我只是改变:

            type: String,

            formType: String,

并且有效。

请参阅:https://github.com/Automattic/mongoose/issues/1760

答案 1 :(得分:9)

允许在名为type的属性上明确定义类型规则,并且不会抛出错误。像这样:

type: {type: String}

答案 2 :(得分:5)

尝试将类定义更改为:

 public KafkaProducer(String zookeeperAddress, String topic) throws IOException,
        KeeperException, InterruptedException {

    this.zookeeperAddress = zookeeperAddress;
    this.topic = topic;

    ZooKeeper zk = new ZooKeeper(zookeeperAddress, 10000, null);
    List<String> brokerList = new ArrayList<String>();

    List<String> ids = zk.getChildren("/brokers/ids", false);
    for (String id : ids) {
        String brokerInfoString = new String(zk.getData("/brokers/ids/" + id, false, null));
        Broker broker = Broker.createBroker(Integer.valueOf(id), brokerInfoString);
        if (broker != null) {
            brokerList.add(broker.connectionString());
        }
    }

    props.put("serializer.class", KAFKA_STRING_ENCODER);
    props.put("metadata.broker.list", String.join(",", brokerList));
    producer = new Producer<String, String>(new ProducerConfig(props));
}

这是必需的,因为mongoose无法在没有相关模式的情况下解析对象。现在,当您为内部类对象创建一个新的Schema并在主userSchema中引用它时,mongoose应该能够解析您的对象。

答案 3 :(得分:4)

您的模型定义不正确,您应该修改如下。

// var Schema = mongoose.Schema;
var User = mongoose.model('User',{ 
  email: String, 
  classes: [ {type: Schema.Types.ObjectID, ref: 'Class'}] 
});

var Class1 = new Class({/*yourDataWillBeHere*/})

Class1.save(function(err, classData) {
   var User1 = new User({/*YourDataWillBeHere*/})
   User1.classes.push(classData._id);
   User1.save(function(err, userData) {
      //make something with userData object 
   })
})

然后,您可以使用populate()这样的

来获取数据
User
.find()
.populate('classes')
.exec()

答案 4 :(得分:1)

仅供更新

现在,Mongoose支持子文档,这是嵌套数组的文档化方法,

If i < dgv.RowCount - 1 Then

<强>来源

http://mongoosejs.com/docs/schematypes.html

答案 5 :(得分:1)

使用猫鼬5.7.0+和双嵌套模式时,我遇到了类似的问题。

除了与关键字type无关,而是猫鼬验证错误。

https://github.com/Automattic/mongoose/issues/8472

临时解决方法:对子模式使用Schema.Types.Mixed

答案 6 :(得分:0)

默认情况下,如果模式中有一个键为'type'的对象,mongoose会将其解释为类型声明。

// Mongoose interprets this as 'loc is a String'
var schema = new Schema({ loc: { type: String, coordinates: [Number] } });

更改typeKey:

var schema = new Schema({
  // Mongoose interpets this as 'loc is an object with 2 keys, type and coordinates'
  loc: { type: String, coordinates: [Number] },
  // Mongoose interprets this as 'name is a String'
  name: { $type: String }
}, { typeKey: '$type' }); // A '$type' key means this object is a type declaration

链接:http://mongoosejs.com/docs/guide.html#typeKey