18

Mongoose に付属する検証機能が気に入っています。これを使用するかどうかを検討し、オーバーヘッドを我慢します。マングーススキーマを作成するときに親コレクションへの参照を提供するかどうかは誰にも分かりますか?(子スキーマで、親オブジェクトのオブジェクトIDをフィールドとして指定します)これは、ドキュメントを保存しようとするたびに参照されたオブジェクト ID の存在について親コレクションをチェックしますか?

4

6 に答える 6

23

私はミドルウェアでそれを行っており、検証時に要素の検索を実行しています:

ExampleSchema = new mongoose.Schema({

    parentId: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Example'
    }

});

ExampleModel = mongoose.model('Example', ExampleSchema);

ExampleSchema.path('parentId').validate(function (value, respond) {

    ExampleModel.findOne({_id: value}, function (err, doc) {
        if (err || !doc) {
            respond(false);
        } else {
            respond(true);
        }
    });

}, 'Example non existent');
于 2013-11-20T03:15:44.857 に答える
3

いいえ、ObjectId別のコレクションへの参照としてスキーマで定義されているフィールドは、保存時に参照されたコレクションに存在するものとしてチェックされません。必要に応じて、Mongoose ミドルウェアで実行できます。

于 2013-08-29T17:23:15.237 に答える
1

このスレッドは非常に役に立ちました。これが私が思いついたものです。

このミドルウェア (とにかくその 1 つだと思います) は、フィールドで提供された ID の参照モデルをチェックします。

const mongoose = require('mongoose');

module.exports = (value, respond, modelName) => {
    return modelName
        .countDocuments({ _id: value })
        .exec()
        .then(function(count) {
            return count > 0;
        })
        .catch(function(err) {
            throw err;
        });
}; 

モデル例:

const mongoose = require('mongoose');
const uniqueValidator = require('mongoose-unique-validator');
const Schema = mongoose.Schema;
const User = require('./User');
const Cart = require('./Cart');
const refIsValid = require('../middleware/refIsValid');

const orderSchema = new Schema({
    name: { type: String, default: Date.now, unique: true },
    customerRef: { type: Schema.Types.ObjectId, required: true },
    cartRef: { type: Schema.Types.ObjectId, ref: 'Cart', required: true },
    total: { type: Number, default: 0 },
    city: { type: String, required: true },
    street: { type: String, required: true },
    deliveryDate: { type: Date, required: true },
    dateCreated: { type: Date, default: Date.now() },
    ccLastDigits: { type: String, required: true },
});

orderSchema.path('customerRef').validate((value, respond) => {
    return refIsValid(value, respond, User);
}, 'Invalid customerRef.');

orderSchema.path('cartRef').validate((value, respond) => {
    return refIsValid(value, respond, Cart);
}, 'Invalid cartRef.');

orderSchema.path('ccLastDigits').validate(function(field) {
    return field && field.length === 4;
}, 'Invalid ccLastDigits: must be 4 characters');

orderSchema.plugin(uniqueValidator);

module.exports = mongoose.model('order', orderSchema);

私は非常に新しい開発者なので、フィードバックは非常に貴重です!

于 2019-12-09T19:20:59.047 に答える