我制作了2个模式,一个使用客户端,第二个使用设备。当我发布添加新的“客户端”的表单时,将其重定向到添加“设备”的第二个表单,它应将其推送到客户端集合中。我得到的是错误“无法读取null的属性'devices'”。我观察到在完成第一个表单后,devices元素没有添加到db中。我认为这与架构有关。我尝试将其存储为数组,使用引用并仅创建一个模式,但没有一个起作用。 当我将元素存储为数组时,我以前的项目工作了。然后push可以正常工作,因为它正在创建一个空数组,以后可以用push来填充它。
ClientSchema
const mongoose = require('mongoose'),
passportLocalMongoose = require('passport-local-mongoose'),
Devices = require('../schema/Devices');
const ClientSchema = new mongoose.Schema({
firstName: {type: String,required:true},
lastName: {type: String,required:true},
contact: {type: String,required:true},
address: String,
nip: String,
email: {type: String,unique: true,required: true},
devices: [{
type: mongoose.Schema.Types.ObjectId,
ref: 'Devices'
}],
manufacturer: String,
model: String,
imei: String,
warranty: Boolean,
});
module.exports = mongoose.model('Client',ClientSchema);
UserSchema
const mongoose = require('mongoose'),
passportLocalMongoose = require('passport-local-mongoose');
const UserSchema = new mongoose.Schema({
username: {type: String, unique:true,required: true},
password: String,
dateOfBirth: {type: String,required:true},
firstName: {type: String,required:true},
lastName: {type: String,required:true},
email: {type: String,unique: true,required: true},
resetPasswordToken: String,
resetPasswordExpires: Date,
isAdmin: {type:Boolean, default:false}
})
UserSchema.plugin(passportLocalMongoose);
module.exports = mongoose.model('User',UserSchema);
表格发布
router.post('/addDevice',(req,res)=>{
console.log(req.params.id);
Client.findById(req.params.id,(err,client)=>{
if(err){
console.log(err);
}else{
Devices.create(req.body.device,(err,device)=>{
if(err){
console.log(err);
} else{
console.log(device);
client.devices.push(device);
client.save();
req.flash('success','Urządzenie przypisane');
res.redirect('/devices');
}
})
}
});
});
在客户端集合中创建一个名为“设备”的元素,以后我可以将其推送到json对象。