【发布时间】:2019-08-13 20:21:00
【问题描述】:
如果键在其中没有值,我正在尝试从 js 对象中删除键。
我尝试使用 delete foundBrief.Contents.url 但没有奏效。我这样做是为了 alexa flash 简报技能。如果重定向 url 为空,则会引发错误,如果它为空,我必须删除该属性 url。
内容架构:
var contentSchema = new mongoose.Schema({
_id : { type: String, default: uuid.v1},
date: Date,
titleText: String,
mainText: String,
Url: String,
author:{
id: {
type: mongoose.Schema.Types.ObjectId,
ref: "User"
},
username: String
}
},{
versionKey: false
});
使用路由在 url 上显示 json 对象:
router.get("/:id/abcd.json", function(req, res) {
Brief.findById(req.params.id)
.populate("contents")
.exec(function(err, foundBrief) {
if (err) {
console.log(err);
} else {
console.log(foundBrief.contents);
//[{"uid":"00a3b980-4ccc-11e9-ab44-dd6a45baec41","date":"2019-03-22T02:30:00.000Z","title":"title test","main":"content text","Url":""}]
foundBrief.contents.forEach(function(element) {
if(element.Url === ""){
delete element.Url;
}
});
}
});
});
有这个
[
{
uid: "00a3b980-4ccc-11e9-ab44-dd6a45baec41",
date: "2019-03-22T02:30:00.000Z",
title: "title test",
main: "content text",
Url: ""
}
];
想要这个
[
{
uid: "00a3b980-4ccc-11e9-ab44-dd6a45baec41",
date: "2019-03-22T02:30:00.000Z",
title: "title test",
main: "content text"
}
];
【问题讨论】:
-
foundBrief.contents.forEach(...)应该可以工作。你能创建一个最小的 sn-p 来重现这个问题吗?
标签: javascript node.js json express mongoose