gpt4 book ai didi

arrays - Mongoose save() 不更新数据库文档中数组中的值

转载 作者:IT老高 更新时间:2023-10-28 11:06:13 25 4
gpt4 key购买 nike

我正在尝试使用 GUI 更新集合(单元)中的文档,并且在更新后我想更新集合(用户)中的值(user.Units,它是单元名称的数组)。如果数组长度只有 1 个元素,它会被更新并显示在数据库中并且一切正常,但是当 Array of Units 有多个元素时,我尝试通过 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 });

最佳答案

也许通知 mongooose 数据集发生了这样的变化:

doc.markModified('pathToYourAttribute') 

来自文档 http://mongoosejs.com/docs/schematypes.html

person.anything = { x: [3, 4, { y: "changed" }] }; 
person.markModified('anything');

希望对你有帮助!

关于arrays - Mongoose save() 不更新数据库文档中数组中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24618584/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com