答案
这固定:mongoose.model('User').findByIdAndUpdate(...
虽然看起来不对。应该是另一种要求这种方式。会搞清楚。
我有一个注册表单,用户可以在其中检查角色,以创建候选人或雇主帐户。让我们说,用户选择了雇主,然后mongoose post hook将被触发在雇主集合中创建雇主并返回employer._id,以便我可以将其保存到用户集合作为参考。在最后一个代码段中,findByIdAndUpdate
未被触发并以静默方式失败。记录,仅输出a
。
user.js(用户模型)
const mongoose = require('mongoose');
const { Schema } = mongoose;
const bcrypt = require('bcrypt-nodejs');
const {
updateUserWithEmployerId,
updateUserWithCandidateId
} = require('../api/user');
const { createCandidate } = require('../api/candidate');
const { createEmployer } = require('../api/employer');
const userSchema = new Schema({
firstName: String,
lastName: String,
email: {
type: String,
unique: true,
lowercase: true
},
password: String,
role: {
type: String,
enum: ['candidate', 'employer']
},
_employerId: {
type: Schema.Types.ObjectId,
ref: 'Employer'
},
_candidateId: {
type: Schema.Types.ObjectId,
ref: 'Candidate'
}
}, {
timestamps: true
});
userSchema.post('save', function(doc, next){
if(doc.role === 'employer'){
return createEmployer(doc._id)
.then(response => updateUserWithEmployerId(doc._id, response.employer._id))
// .catch(error => next(error))
// .catch(error => response.status(500).send(error))
}else if(doc.role === 'candidate'){
return createCandidate(doc._id)
.then(response => updateUserWithCandidateId(doc._id, response.candidate._id))
.catch(error => response.status(500).send(error))
}else{
throw new Error('User role not found!');
}
next();
});
const ModelClass = mongoose.model('User', userSchema);
module.exports = ModelClass;
employer.js(这不是模特)
const Employer = require('../models/employer');
exports.createEmployer = (userId) => {
return new Promise(function(resolve, reject){
const employerInstance = new Employer({ _userId: userId });
if(employerInstance){
employerInstance.save((err, employer) => {
if(err){
reject({ message: "Error occured while creating employer!" });
}else{
resolve({ employer: employer });
}
});
}else{
reject({ message: "Error occured while creating employer!" });
}
});
};
user.js(不是模特)
const User = require('../models/user');
exports.updateUserWithEmployerId = (userId, employerId) => {
return new Promise(function(resolve, reject){
console.log("a");
User.findByIdAndUpdate(userId, { _employerId: employerId }, { new: true },
(err, user) => {
console.log("user:", user);
if(err){
console.log("b");
reject({ message: "Error occured while updating user with employer id!" });
}else{
console.log("c");
resolve({ user: user });
}
});
console.log("d");
});
};