【发布时间】:2019-03-21 16:59:31
【问题描述】:
当我更新我的用户资料时,我的用户模型上位置内部的字段附近被删除,这是我的用户模型,您可以在其中看到位置内部的附近:
const userSchema = new Schema({
name: {
type: String,
required: 'Please supply a name',
trim: true
},
location: {
type: {
type: String,
default: 'Point'
},
coordinates: [{
type: Number,
required: 'You must supply coordinates!'
}],
address: {
type: String,
required: 'You must supply an address!'
},
vicinity: {
type: String,
},
},
});
然后我有一个更新用户的控制器,其中我有一个更新对象,并且附近不存在,因为我不想更新它,我只想将附近保存在寄存器上,而不是更新它:
exports.updateAccount = async (req, res) => {
req.body.location.type = 'Point';
const updates = {
email: req.body.email,
name: req.body.name,
photo: req.body.photo,
genres: req.body.genres,
musicLinks: req.body.musicLinks,
location: {
type: req.body.location.type,
coordinates: [
req.body.location.coordinates[0],
req.body.location.coordinates[1],
],
address: req.body.location.address,
// vicinity: req.body.location.vicinity,
}
};
if(!updates.photo) delete updates.photo
const user = await User.findOneAndUpdate(
{ _id: req.user._id },
{ $set: updates },
{ new: true, runValidators: true, context: 'query' }
);
req.flash('success', 'Updated the profile!');
res.redirect('back');
};
但是每次我更新用户个人资料时,邻近字段都会被删除,还要注意,在我为用户提交更新的表单中,没有邻近字段,因此它不会发送任何数据进行更新。
我猜是因为在控制器上我有一个更新对象,例如:
location: {
type: req.body.location.type,
coordinates: [
req.body.location.coordinates[0],
req.body.location.coordinates[1],
],
address: req.body.location.address,
// vicinity: req.body.location.vicinity,
}
及其缺失的 vecinity。数据库会尝试保存整个位置对象,但由于附近没有它会被删除。
如果是这样的话.. 我如何对 mongo db 说要保留 db 上的值而不是删除它?谢谢
【问题讨论】:
标签: node.js mongodb express mongoose