Mongo schema, array of string with unique values

const express = require('express');
const router = express.Router();
const mongoose = require('mongoose');
const _ = require('underscore');

let sampleSchema = new mongoose.Schema({
  name: {
    type: 'String',
    unique: true
  },
  tags: [{
    type: 'String'
  }]
})
sampleSchema.pre('save', function (next) {
  this.tags = _.uniq(this.tags);
  next();
});
const Sample = mongoose.model('sample', sampleSchema, 'samples');


router.post('/sample', function (req, res, next) {
  const sample = new Sample(req.body);

  sample.save()
    .then((sample) => {
      return res.send(sample);
    })
    .catch(err => {
      return res.status(500).send(err.message);
    })
});

I've come to the conclusion that this is impossible to do via Mongoose Schema.

JSON schema is done like so.

let schema = {
   name: { type: 'string' }
   tags: { 
      type: 'array',
      items: { type: 'string', uniqueItems: true }
   }
}

I'll validate with JSON schema before creating Mongo Document.


This method builds on Med's answer, handles references, and done completely in scheme validation.

let sampleSchema = new mongoose.Schema({
    strings: [{type: 'String'}],
    references: [{type: mongoose.Schema.Types.ObjectId, ref: 'Reference'],
});

sampleSchema.pre('save', function (next) {

    let sample = this;

    sample.strings = _.uniq(sample.strings, function(i) {return (i._id) ? i._id.toString() : i;});
    sample.references = _.uniq(sample.references, function(i) {return (i._id) ? i._id.toString() : i;});

    return next();

});