创建一个模式,其中一个字段包括一个引用另一个模式objectId的objectId和一个字符串

时间:2017-06-23 06:20:46

标签: javascript mongoose

这是代码。以下和关注者无法工作。换句话说,我无法将像{"user1", objectId1}这样的对象推送到这两个数组。 是否允许包含对象ID和字符串名称的字段? 感谢您的帮助。

The error is: 
   { CastError: Cast to ObjectId failed for value "{ userId: '594ad9106f636d4e244d1f11', username: 'aa' }" at path "followers"
var userSchema = mongoose.Schema({
        username: {type: String, unique: true},
        password: String,
        firstName: String,
        lastName: String,
        roles: [{
            type: String, default: 'USER', enum: ['USER', 'ADMIN']
        }],
        facebook: {
            id: String,
            token: String
        },
        email: String,
        phone: String,
        websites: [{type: mongoose.Schema.Types.ObjectId, ref: "ProjectWebsiteModel"}],
        dateCreated: {type: Date, default: Date.now},
        followings: [{username: String, type: mongoose.Schema.Types.ObjectId, ref: "ProjectUsereModel"}],
        followers:  [{username: String, type: mongoose.Schema.Types.ObjectId, ref: "ProjectUsereModel"}]

}, {collection: "projectuser"});

1 个答案:

答案 0 :(得分:0)

试试这个:

followings: [{
    username: String, 
    id: {
        type: mongoose.Schema.Types.ObjectId,
        ref: "ProjectUsereModel"
    }
}],
followers:  [{
    username: String,
    id: {
        type: mongoose.Schema.Types.ObjectId,
        ref: "ProjectUsereModel"
    }
}]

...所以你的'跟随'和'粉丝'数组将包含属性'username'和'id'的对象。