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.