2017-08-12 66 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 –

相關問題