从客户端收到数据后,我想添加一个新文档或更新(如果已存在)。对于所有未定义的参数,我想删除现有的密钥。
处理数据并应执行保存/更新数据的功能如下:
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,但不知道为什么未删除未定义值的键。
答案 0 :(得分:0)
也许试试这个,你有... ...
var upsertData = event.toObject();
delete upsertData._id;
将其添加到......
之下for (var theKey in upsertData) {
if (upsertData.hasOwnProperty(theKey)) {
if (!upsertData[theKey]) {
delete upsertData[theKey];
}
}
}
或者我错过了什么?