Babalola Rotimi
Babalola Rotimi

Reputation: 339

Referencing Object Id not working in Mongoose 4.11.6

I have this problem. Basically, I have 2 schemas - a User schema and a Document schema. The Document schema has an owner which references the _id field of documents in the User collection.

The problem is that I am still able to save documents in the Document collection with owner ids that do not exist in the User collection which should not be so.

Here is my User schema and Document schema respectively

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);

And the Document Schema

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);

Any help will be appreciated thanks.

Upvotes: 0

Views: 357

Answers (1)

Shaishab Roy
Shaishab Roy

Reputation: 16805

For that situation you can add pre save function in your Document schema that will call before save your Document.

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);

Upvotes: 2

Related Questions