Collection2 not validating uniqueness


#1

Hi, I’m trying to validate a uniqueness of a field using aldeed:collection2 but the error never get passed to the client and raise a mongodb error:

MongoError: E11000 duplicate key error collection: meteor.Posts index: c2_fbPageId dup key: { : "xxxxxxx" }

This is the schema definition:

import { Mongo } from 'meteor/mongo';
import { SimpleSchema } from 'meteor/aldeed:simple-schema';

const Posts = new Mongo.Collection('Posts');
export default Posts;

Posts.schema = new SimpleSchema({
  title: {
    type: String,
    label: 'The title of the post.',
  },
  fbPageid: {
    type: String,
    unique: true,
    index: true,
    label: 'The id of the page associated to the post.',
  },
  body: {
    type: String,
    label: 'The body of the post.',
  }
});

Posts.attachSchema(Posts.schema);

And this is the method I’m calling:

import { Meteor } from 'meteor/meteor';
import { SimpleSchema } from 'meteor/aldeed:simple-schema';
import { ValidatedMethod } from 'meteor/mdg:validated-method';
import Posts from './posts';

export const upsertPost = new ValidatedMethod({
  name: 'Posts.methods.upsert',
  validate: new SimpleSchema({
    _id: { type: String, optional: true },
    title: { type: String },
    fbPageId: { type: String },
    body: { type: String },
  }).validator(),
  run(post) {
    try {
      return Posts.upsert({ _id: post._id }, { $set: post });
    } catch (error) {
      throw new Meteor.Error('some', error.invalidKeys);
    }
  },
});

When trying to upsert a post without title the validation works and return the error but not with unique.

Any ideas?


#2

Have you tried preventing the client-side simulation by wrapping the run code in a Meteor.isServer?

run(post) {
  if (Meteor.isServer) {
    try {
      return Posts.upsert({ _id: post._id }, { $set: post });
    } catch (error) {
      throw new Meteor.Error('some', error.invalidKeys);
    }
  }
},

#3

I got the same error