Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongo schema, array of string with unique values

I'm creating the schema for a mongo document and I can do everything except prevent duplicates in a non-object array.

I'm aware of the addToSet, but I'm referring to Mongo Schema.

I don't want to check on Update using $addToSet, rather I want this to be part of my schema validation.

Example below.

let sampleSchema = {
   name: { type: 'String', unique: true },
   tags: [{ type: 'String', unique: true }]
}

The above snippet prevents name from having duplicate values. It allows tags to be stored as a string array.

But.. I cannot limit the array to be unique strings.

{ name: 'fail scenario', tags: ['bad', 'bad', 'array']}

I'm able to insert this record which should be a fail scenario.

like image 669
Proximo Avatar asked Jan 22 '17 08:01

Proximo


1 Answers

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);
    })
});
like image 156
Med Lazhari Avatar answered Oct 17 '22 07:10

Med Lazhari