gpt4 book ai didi

javascript - 无法使用 upsert 删除键

转载 作者:行者123 更新时间:2023-11-28 07:07:16 25 4
gpt4 key购买 nike

收到客户端的数据后,我想添加新文档或更新(如果已存在)。对于所有未定义的参数,我想删除现有的键。

处理数据并执行保存/更新数据的函数如下:

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并且不知道为什么未定义值的键没有被删除。

最佳答案

也许试试这个,你有...

var upsertData = event.toObject();
delete upsertData._id;

将其添加到下面...

for (var theKey in upsertData) {
if (upsertData.hasOwnProperty(theKey)) {
if (!upsertData[theKey]) {
delete upsertData[theKey];
}
}
}

还是我错过了什么?

关于javascript - 无法使用 upsert 删除键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31613305/

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