我正在尝试使用GUI更新集合(单位)中的文档,并在更新后,我想更新集合(用户)中的值(user.Units,它是一个单元名称数组)。如果数组长度只是1个元素,它会更新并显示在数据库中,一切运行良好,但是当单元数组有多个元素时,我尝试通过for循环更新它,它显示它会更新但是当我检查数据库它仍未更新。
当我通过循环更新值时,我真的无法弄清楚为什么它不更新数据库。
整个编辑和更新功能: -
edit_unit: function (req, res, next) {
var Data = req.body;
Client_data.Unit.findById(req.params.unitId, function (err, unit) {
var error = false;
if (err) {
error = err;
} else if (!unit) {
error = "FATAL: unable to look up Unit #" + req.params.unitId;
} else {
switch(req.body.name) {
case 'Icon':
var Icon = unit.Icon;
User.find({"Units":Icon}, function (err, users) {
if (err)
console.log(err);
users.forEach(function (u) {
if (u.Units.length > 1) {
for (var i = 0; i <= u.Units.length; i++) {
if(u.Units[i] == Icon) {
u.Units[i] = req.body.value;
}
}
}
else {
u.Units = req.body.value;
}
u.save(u);
});
});
unit[req.body.name] = req.body.value;
break;
case 'Description':
unit[req.body.name] = req.body.value;
break;
default:
unit[req.body.name] = req.body.value;
break;
}
var data = JSON.stringify(req.body);
unit.save();
res.writeHead(200, {
'Content-Length': data.length,
'Content-Type': 'application/json'
});
res.end(data);
}
});
}
req.body: -
{ name: 'Icon',
value: 'Health Utility 22c',
pk: '5395ed107cd92dc40eaafb56'
}
用户架构:
var userSchema = mongoose.Schema({
UserName: { type: String, required: true },
Password: { type: String },
FirstName: { type: String, required: true },
LastName: { type: String, required: true },
CompanyName: { type: String },
PhoneNumber: { type: Number },
StartDate: { type: Date, required: true },
EndDate: { type: Date, required: true, default: new Date('9999-12-12') },
ClientID: { type: ObjectId, ref: 'Client', default: null },
DepartmentID: { type: ObjectId, ref: 'Department' },
ManagerID: { type: ObjectId, ref: 'User', default: null},
Units: [ { type: String, required: true } ],
UserList: { type: Array, default:[]},
Access: [{ type: String, enum: ['DEMO', 'USER','MANAGER','ADMINISTRATOR','OWNER']}],
Credentials: { type: String },
AFTE: { type: Number},
SessionID: { type: String, default: null }
}, { safe: true });
答案 0 :(得分:59)
也许通知mongooose数据集已经改变如下:
doc.markModified('pathToYourAttribute')
来自文档http://mongoosejs.com/docs/schematypes.html
person.anything = { x: [3, 4, { y: "changed" }] };
person.markModified('anything');
希望它有所帮助!
答案 1 :(得分:5)
请参阅this issue。解决此问题的一种方法是不通过经典数组索引方法更新数组。这样做
doc.array.set(index, value);
而不是
doc.array[index] = value;
答案 2 :(得分:0)
我用以下语句替换了保存方法: Client_data.Unit.updateOne({_ id:unit._id},unit);