2017-08-12 5 views
0

この問題があります。基本的には、私は2つのスキーマを持っています - ユーザースキーマとドキュメントスキーマ。ドキュメントスキーマはUserコレクション内の_idフィールドのドキュメントを参照するownerを持っています。参照対象のオブジェクト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); 

です。あなたがsaveあなたDocument前に呼び出しますあなたのDocumentスキーマにpre save機能を追加することができ、その状況については

+1

Mongodbはデータの一貫性を提供しません。この機能が必要な場合は、RDBMSを使用してください。 – alexmac

答えて

1

+0

これはうまくいった!ありがとう@シャイシャブロイ –

関連する問題