无法使用 upsert 删除键
Posted
技术标签:
【中文标题】无法使用 upsert 删除键【英文标题】:Unable to delete keys with upsert 【发布时间】:2015-10-15 06:57:43 【问题描述】:收到来自客户端的数据后,我想添加一个新文档或更新如果它已经存在。对于所有未定义的参数,我想删除现有的键。
处理数据并执行保存/更新数据的函数如下:
router.post('/saveEvent', isAuthenticated, function(req, res)
var eventId = req.body.eventId;
console.log(eventId);
var timelineId = req.body.timelineId;
var strEventStart = req.body.eventStart;
var strEventEnd = req.body.eventEnd;
var mediaURI = req.body.mediaURI;
var note = req.body.note;
var title = req.body.title;
var eventIdToSave;
var event = new Event(_timeline: timelineId, title: title, description: note, mediaURI: mediaURI, eventStart: strEventStart, eventEnd: strEventEnd);
console.log("Updated event: " + event);
if(!(eventId == "" | eventId == undefined))
eventIdToSave = eventId;
else
eventIdToSave = event._id;
var upsertData = event.toObject();
delete upsertData._id;
console.log("event: " + upsertData);
Event.update(_id: eventIdToSave, upsertData, upsert: true, function(err)
if(err)
console.log(err);
else
if(eventId == "" | eventId == undefined)
Timeline.findByIdAndUpdate(
timelineId,
$push: "events": eventIdToSave,
safe: true, upsert: true, new : true,
function(err, model)
console.log(err);
if(!err)
console.log("added new event to timeline");
res.json(Successful: true);
);
else
res.json(Successful: true);
);
);
以下是接收数据的控制台输出示例:
Updated event: _timeline: 55b21588c4a50f345c928e2c,
title: 'This is perfect!',
description: '<div><b style="line-height: 1.42857143;">This image was taken somewhere in Europe.</b><br></div>',
mediaURI: undefined,
eventStart: Thu Jul 30 2015 23:26:00 GMT+0200 (CEST),
eventEnd: undefined,
_id: 55b24aff323dc6dd6d7378ea,
duration: false
在本例中,mediaURI 和 eventEnd 未定义,但未删除键;这是经过上述操作后从集合中检索到的示例数据:
events:
[ _id: 55b23d265821141f65bb515d,
mediaURI: 'https://dl.dropboxusercontent.com/1/view/xxxxx.jpg',
description: '<div><b style="line-height: 1.42857143;">This image was taken somewhere in Europe.</b><br></div>',
title: 'This is perfect!' ]
有谁知道删除现有文档中未从客户端收到参数的所有键的正确方法是什么?
我检查了this post,不知道为什么没有删除未定义值的键。
【问题讨论】:
【参考方案1】:也许试试这个,你有...
var upsertData = event.toObject();
delete upsertData._id;
在下面添加...
for (var theKey in upsertData)
if (upsertData.hasOwnProperty(theKey))
if (!upsertData[theKey])
delete upsertData[theKey];
还是我错过了什么?
【讨论】:
以上是关于无法使用 upsert 删除键的主要内容,如果未能解决你的问题,请参考以下文章
Centos6.5 编译安装python3.5版本,无法使用退格键方向键删除键等