0

Problem

My goal is to have a unique field within a subset of my collection. In particular the serial number within a product art should be unique. So there can be two similar serial numbers if the art is different but only one if the art is the same.

To check that I wanted to use the mongoose pre middleware (if there is not a better solution on the schema level).

implant.schema.coffee

ImplantModel = require('./implant.model.js')
...
implantSchema = mongoose.Schema({
  art: {
    type: String,
    required: true
  },
  serialNr: {
    type: String,
    required: true
  },
  ...

validateImplant = (data, next) ->
  err = ""
  if !data.art? || data.art == ""
    err += "Keine Implantatbezeichnung vorhanden!\n"
  if !data.serialNr? || data.serialNr == ""
    err +=  "Keine Seriennummer vorhanden!\n"

  return next err if err != ""

  inspect ImplantModel
  # ImplantModel.findOne({serialNr: data.serialNr, art: data.art}, (err, implantFound) ->
  #   return next err if err?
  #   return next "Eine Seriennummer darf nur einmlaig pro Hersteller angelegt werden!"
  #   return next null
  # )
  next

implant.model.coffee

mongoose = require('mongoose')

implantSchema = require('./implant.schema.js').getSchema()

try
  module.exports = mongoose.model('Implant', implantSchema)
catch err
  module.exports = mongoose.model('Implant')

The problem is that ImplantModel seems to be {} at that time. I also tried it with this.constructor.findOne as mentioned here How to query from within Mongoose pre hook in a Node.js / Express app? which gives me findOne is not a function

I could perform a query before I call .save method but I guess the hook would be the better place.

Community
  • 1
  • 1
Andi Giga
  • 3,744
  • 9
  • 38
  • 68
  • Why not use a unique index to enforce this constraint? – JohnnyHK Jan 22 '16 at 14:51
  • How can I do that with a SUBSET of the collection. I don't want it to be unique over the whole collection, just within e.g. all docs which have `art: xy` That would be even better if possible. Eg. `{serialNr: "123", art:"Apple"}`, `{serialNr: "123", art:"Apple"}` should not be allowed while `{serialNr: "123", art:"Apple"}`, `{serialNr: "123", art:"Banana"}` should be allowed – Andi Giga Jan 22 '16 at 15:07
  • You can create a compound unique index over the combination of the `art` and `serialNr` fields, as in [this answer](http://stackoverflow.com/questions/16061744/mongoose-how-to-define-a-combination-of-fields-to-be-unique/16067314#16067314). – JohnnyHK Jan 22 '16 at 15:12
  • Will the old index `_id` be kept? And there is something mentioned about a performance loss, or will this just be if it is created automatically? http://mongoosejs.com/docs/guide.html#indexes – Andi Giga Jan 26 '16 at 09:33

0 Answers0