These are chat archives for Automattic/mongoose

26th
May 2018
Ian Arsenault
@ianarsenault
May 26 2018 13:41
Hey guys, I'm trying to index email in my schema, but I'm getting TypeError: schema.index is not a function
const schema = {
  email: {
    type: String,
    required: [true, 'Email is required'],
    validate: [validator.isEmail, 'Invalid email']
  },
  password: {
    type: String,
    required: [true, 'Password is required'],
    minlength: [8, 'Your password must be at least 8 characters'],
  }
}

schema.index({ email: 1 }, { unique: true})


const Users = dbfactory("Users", schema)
schema.index({ email: 1 }, { unique: true})
             ^
is crashing the app
Kev
@lineus
May 26 2018 13:47
@ianarsenault should be const schema = new mongoose.Schema( instead of just an object
you can pass a POJO into model and it will work, but if you're going to call methods from mongoose.Schema on it, you'll need to create instance of Schema explicitly
Ian Arsenault
@ianarsenault
May 26 2018 15:32

I'm doing that in another file and passing the const schema object in

const dbfactory = require('./database.js')
const schema = {....}
const Users = dbfactory("Users", schema)

database.js

let mongoose = require('mongoose')
let Schema = mongoose.Schema

module.exports = (schemaName, schemaObj) => {
  return mongoose.model(schemaName, new Schema(schemaObj))
};
I was able to create unique index on email by doing
email: {
    type: String,
    required: [true, 'Email is required'],
    validate: [validator.isEmail, 'Invalid email'],
    index: { unique: true }
  },
I ended up adding mongoose-unique-validator package and have been able to successfully check for existing emails with it
Ian Arsenault
@ianarsenault
May 26 2018 15:42
Thanks for your help @lineus
I also found my issue with the original schema.index({ email: 1 }, { unique: true}) it was because I did not put it after the creation of the schema. so it should've been
....
const Users = dbfactory("Users", schema)
Users.schema.index({ email: 1 }, { unique: true})
`