我建立了一个更新子文档的node.js api。下面是子文档的post调用:
.put(function(req, res) {
member.findById(req.params.member_id, function(err, member) {
if (err)
res.send(err);
console.log("old: " + member);
member.address[req.params.address_id].address_type = req.body.address_type;
member.address[req.params.address_id].street1 = req.body.street1;
member.address[req.params.address_id].street2 = req.body.street2;
member.address[req.params.address_id].City = req.body.City;
member.address[req.params.address_id].State = req.body.State;
member.address[req.params.address_id].Zip = req.body.Zip;
member.address[req.params.address_id].Lat = req.body.Lat;
member.address[req.params.address_id].Lng = req.body.Lng;
console.log("new: " + member);
member.save(function(err) {
if (err)
res.send(err);
res.json({message:'Address Updated!!!'});
})
})
})
两个console.log行证明该对象是在findById调用中找到的,然后在遍历数组后更新。日志证明内存中的对象实际上已更新。
但是,在执行.save()
调用时,我收到了成功消息,但mongodb没有任何变化。
我没有错误,没有警告,没有。它说成功,但没有变化。 我该如何排除故障?
这是我的地址模型:
var mongoose = require('mongoose'),
Schema = mongoose.Schema
var AddressSchema = Schema({
Address_type : String,
street1 : String,
street2 : String,
City : String,
State : String,
Zip : Number,
Lat : Number,
Lng : Number
});
module.exports = mongoose.model('Address', AddressSchema);
这里是父模型,成员:
var mongoose = require('mongoose'),
Schema = mongoose.Schema
var Address = require('./address');
var Award = require('./award');
var MemberSchema = Schema({
FName : String,
LName : String,
address: [Address.Schema],
phone : {
type : String,
number : String
},
email: String,
gender: String,
DOB: Date,
rank : {
level : String,
updated: { type: Date, default: Date.now }
},
Awards : {
personal : Boolean,
award : [Award.Schema],
granted: { type: Date, default: Date.now }
}
});
module.exports = mongoose.model('Member', MemberSchema);
答案 0 :(得分:2)
当您通过索引更新Mongoose文档的数组元素时,它不会触发数组的更改检测,因此Mongoose不知道保存它(请参阅FAQ)。
要手动触发更改检测,您可以在致电member.save
之前致电markModified
:
member.markModified('address');
要帮助解决这些类型的问题,请启用Mongoose的调试输出,通过在启动代码中添加以下内容来查看它对本机驱动程序的实际调用:
mongoose.set('debug', true);