2017-08-12 40 views
0

我有这个问题。基本上,我有2个模式 - 用户模式和文档模式。文档模式有一个owner,它引用User集合中文档的_id字段。引用对象ID在Mongoose中不工作4.11.6

问题是,我仍然能够使用User集合中不存在的所有者ID保存Document集合中的文档,但不应该如此。

这是我User架构和Document模式分别

const UserSchema = new Schema({ 
    firstName: { 
    type: String, 
    required: true, 
    }, 
    lastName: { 
    type: String, 
    required: true, 
    }, 
email: { 
    type: String, 
    validate: [{ validator: value => isEmail(value), msg: 'Invalid email.' 
    }], 
    unique: true, 
    required: true, 
}, 
password: { 
    type: String, 
    required: true, 
}, 
isAdmin: { 
    type: Boolean, 
    default: false, 
}, 
}, { 
timestamps: true, 
}); 

const User = mongoose.model('User', UserSchema); 

和文档架构

const DocumentSchema = new Schema({ 
    title: { 
     type: String, 
     required: true, 
    }, 
    text: { 
    type: String, 
    }, 
    access: { 
    type: String, 
    enum: ['public', 'private'], 
    default: 'public', 
    }, 
owner: { 
    type: Schema.Types.ObjectId, 
    ref: 'User', 
    required: true, 
    }, 
}, { 
timestamps: true, 
}); 

const Document = mongoose.model('Document', DocumentSchema); 

任何帮助将不胜感激感谢。

+1

Mongodb不提供数据一致性。如果您需要此功能,请使用RDBMS。 – alexmac

回答

1

对于这种情况,你可以在你的Document架构添加pre save功能,将你的saveDocument打电话。

const DocumentSchema = new Schema({ 
    // ... 
}, { 
timestamps: true, 
}); 


DocumentSchema .pre("save",function(next) { 
    var self = this; 
    if (self.owner) { 
    mongoose.models['User'].findOne({_id : self.owner }, function(err, existUser){ 
     if(err){ 
     return next(false, err); 
     } 

     if(!existUser) 
     return next(false, "Invalid user reference"); 
     else 
     return next(true); 
    }); 
    } else { 
    next(false, "Owner is required"); 
    } 
}); 

const Document = mongoose.model('Document', DocumentSchema); 
+0

工作正常!谢谢@ Shaishab Roy –