在Mongoose模式中,另一个表的objectId有一个空字段。我想在创建User对象后填充该字段,因为学校对象是在用户对象之后创建的。
用户:
最初我认为使用FindOneandUpdate()函数可以做到这一点,但我没有运气。
有任何想法吗?
company.component.ts
joinCompany(i){
console.log(this.companyArr[i]._id);
this.authService.addmoreUser(this.companyArr[i]._id).subscribe(data =>{
if(data.success){
this.router.navigate(['dashboard']);
}
else{
this.flashMessages.show(data.msg,{cssClass: 'alert-
danger',timeout:3000});
}
})
}
auth.service.js
addmoreUser(id){
id = {companyid:id};
console.log(id);
let headers = new Headers();
headers.append('Authorization', this.authToken);
headers.append('Content-Type','application/json');
return this.http.put('http://localhost:3000/users/pushCompanyintoUser',id,{headers:headers})
.map(res => res.json());
}
companies.js - CRUD文件
router.put('/pushCompanyintoUser', passport.authenticate('jwt', {session:false}), (req, res, next) => {
console.log(req.body);
User.findByIdAndUpdate(req.user._id,{companyid:req.body} , function(err,user) {
if (err) throw res.json({success:false, msg:'Failed to Update user!'});
else res.json({success: true, msg:'User Updated!!'})
});
});
这是从传递给服务器的角度前端然后尝试插入到db。
数据库架构
const UserSchema = mongoose.Schema({
fullname:{ type: String},
email:{ type:String, required:true},
username:{ type:String, unique:true,required:true },
companyid:{ type:mongoose.Schema.Types.ObjectId, ref: 'Company', required:false}, <== (This is the where I am trying to submit to, in an object thats already made)
dob:{ type:String, required:true },
addressline:{ type:String, required:true },
town:{ type:String,required:true },
county:{ type:String,required:true},
country:{ type:String, required:true},
phone:{ type:Number, required:true },
password:{ type:String, required:true }
});
User对象在没有companyid的情况下插入,如何在之后添加companyid。