0
votes

Hi I am learning to use mongoose middleware.

What I want is: When I create a user, it automatically create a userPreference document for that user.

That's why I define a 'save' middleware.

Here is my code:

const mongoose = require('mongoose')

var Schema = mongoose.Schema;
//I define the schema here
const userInfo = new Schema({
  Id:{ type: String,unique:true },
  key:{ type: String, unique: true },

})
const userPreference = new Schema({
    Id:{ type: String,unique:true },
    date:Date,
    color:String
  })

//This is where I define the Model UserPreference , but my code says I didn't define it?
const UserPreference = mongoose.model('userPreference',userPreference); 


//Here I add the middleware
userInfo.post('save', async function() {
      console.log('Middleware begins')
      await this.model("UserPreference").create({Id:this.Id})
});

const UserInfo = mongoose.model('userInfo',userInfo); 

//Here I connectToServer and try to create the user
connectToServer( function( err, res ) {
    if (err) {console.log(err);}
    createUser();
})


async function createUser(){

     var Id = '12345';
     await UserInfo.create({Id:Id,key:'My-key'});


}

When I run my code, the console outputs the Middleware begins (so the middleware fires successfully).UserInfo also creates successfully.

However then userPreference fails to create and I always get this error:

MissingSchemaError: Schema hasn't been registered for model >"UserPreference".Use mongoose.model(name, schema)

I double check I define UserPreference in my code, and it's also before I use that UserPreference model.

const UserPreference = mongoose.model('userPreference',userPreference);

1

1 Answers

1
votes

Because you registered your model with userPreference in:

const UserPreference = mongoose.model('userPreference',userPreference)

So you need to call it in this way:

this.model("userPreference").create({Id:this.Id})

Or:

UserPreference.create({Id:this.Id})