-
-
Save manjeettahkur/b89f6ce4d95110644bc1 to your computer and use it in GitHub Desktop.
Sparse indexes in Mongo with Mongoose
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Assumes you've already somehow configured your db access. I left that part out | |
var mongoose = require("mongoose") | |
var es = new mongoose.Schema({ | |
'firstname': { type: String, required: true }, | |
'lastname': { type: String, required: true }, | |
'email': { type: String, required: true, index: { unique: true, sparse: true }, validate: /\b[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}\b/ }, | |
'departmentId': { type: mongoose.Schema.ObjectId, required: true }, | |
'enddate': String, | |
'active': { type: Boolean, default: true }}) | |
var EmployeeSchemaModel = mongoose.model('employees', es) | |
var DepartmentSchema = new mongoose.Schema({ | |
'name': { type: String, required: true, index: { unique: true } }, | |
'employees' : [ es ] | |
}) | |
var DepartmentSchemaModel = mongoose.model('departments', DepartmentSchema) | |
var a = DepartmentSchemaModel.create({name: "a"}, function(err, d) { | |
if (err) console.log("got error on first"); | |
DepartmentSchemaModel.create({name: "b"}, function(err, e) { | |
console.log("on #2") | |
console.log(err) // we don't get this error | |
}) | |
}) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment