将数组保存为获取Cast to Array的属性时,Mongo DB因值错误而失败

时间:2015-11-17 07:30:19

标签: mongodb mongoose

我有两个模式。

1。项目

var Project = new Schema({
    id: { type: String, required: true, unique: true },
    name: { type: String, required: true, unique: true },
    createdDate: { type: Date, required: true },
    createdBy: { type: String, required: true },
    users: [{type: ProjectUser} ]
});

2。 ProjectUser

var ProjectUser = new Schema({
    id: { type: String, required: true},
    role: { type: String, required: false}
});

我使用

保存
var projectUser = ProjectUser({
    id: createdByUserId,
    role: 'owner'
});
var newProject = Project({
    id: uuid.v1(),
    name: name,
    createdDate: new Date(),
    createdBy: createdByUserId,
    users: [projectUser]
});
return newProject.saveAsync();

但我一直收到这个错误。

{
    "stack": "Error\n    at MongooseError.ValidationError (xxxxxx",
    "message": "Project validation failed",
    "name": "ValidationError",
    "errors": {
        "users": {
            "stack": "Error\n    at MongooseError.CastError (xxxxxx",
            "message": "Cast to Array failed for value \"{ id: '0b8b5e20-8cf4-11e5-b0f9-ad51227a5ce9',\n  role: 'owner',\n  _id: 564ad68d0b1d43e426bc888e }\" at path \"users\"",
            "name": "CastError",
            "kind": "Array",
            "value": [{
                "id": "0b8b5e20-8cf4-11e5-b0f9-ad51227a5ce9",
                "role": "owner",
                "_id": "564ad68d0b1d43e426bc888e"
            }],
            "path": "users"
        }
    }
}

以下是我希望将数据存储为:

{
    "_id": ObjectId("564ad66216f0aba025efe0aa"),
    "id": "5d4fb460-8cfc-11e5-b294-330fd033c64b",
    "name": "test2",
    "createdDate": ISODate("2015-11-17T07:25:22.983Z"),
    "createdBy": "0b8b5e20-8cf4-11e5-b0f9-ad51227a5ce9",
    "users": [{
        id: '0b8b5e20-8cf4-11e5-b0f9-ad51227a5ce9',
        role: 'owner'
    }, {
        id: '0b8b5e20-8cf4-11e5-b0f9-ad53333a5ce9',
        role: 'member'
    }],
    "__v": 0
}

1 个答案:

答案 0 :(得分:0)

项目用户架构

var ProjectUserSchema = new Schema({
    id: { type: String, required: true},
    role: { type: String, required: false}
});

项目架构

var ProjectSchema = new Schema({
    id: { type: String, required: true, unique: true },
    name: { type: String, required: true, unique: true },
    createdDate: { type: Date, required: true },
    createdBy: { type: String, required: true },
    users: [ProjectUserSchema]
});

创建模型&对象

var ProjectUser = mongoose.model('ProjectUser', ProjectUserSchema);
var projectUser = new ProjectUser({
    id: createdByUserId,
    role: 'owner'
});

var Project = mongoose.model('Project', ProjectSchema);
var newProject = new Project({
    id: uuid.v1(),
    name: name,
    createdDate: new Date(),
    createdBy: createdByUserId,
    users: [projectUser]
});

总之,保存您的对象

newProject.saveAsync();