嗨,我正在学习使用猫鼬中间件。
我想要的是: 创建用户时,它将自动为该用户创建一个userPreference文档。
这就是为什么我定义一个“保存”中间件。
这是我的代码:
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'});
}
运行代码时,控制台将输出Middleware begins
(因此中间件将成功触发)。UserInfo也将成功创建。
但是,userPreference无法创建,并且我总是收到此错误:
MissingSchemaError:尚未为模型>“ UserPreference”注册架构。请使用mongoose.model(name,schema)
我仔细检查了一下,我在代码中定义了UserPreference,而且也是在使用该UserPreference模型之前。
const UserPreference = mongoose.model('userPreference',userPreference);
答案 0 :(得分:1)
因为您是通过 userPreference 在以下位置注册模型的:
const UserPreference = mongoose.model('userPreference',userPreference)
因此您需要以这种方式调用它:
this.model("userPreference").create({Id:this.Id})
或者:
UserPreference.create({Id:this.Id})