【发布时间】:2018-01-02 10:50:11
【问题描述】:
我是 JavaScript 和 Node 等的新手,但我很享受开发的经验——我上一次认真的开发是在 90 年代——30 年前我曾经是一名 370 汇编程序员!
我整天都被困在这个问题上。
我的问题是我正在尝试向对象数组中的条目添加一个新元素。我在这里简化了我的代码,希望我正在做一些非常愚蠢和明显错误的事情,尽管我已经在浏览器中的 javascript 中尝试过这个,并且我知道我在吠叫正确的树。
我要做的是向返回的收藏品添加一个新的键/值对。我在这里简化了代码,但本质上价值来自不同的集合。问题是设置新键的行对我在数组收藏品中的对象没有影响。我已经尝试了几种我认为应该有效的方法。
我可以读取返回的对象数组中的键/值,也可以将现有键设置为新值,但设置新键不起作用。
这是我的代码:
var sendJsonResponse = function (res, status, content) {
res.status(status);
res.json(content);
};
var mongoose = require("mongoose");
var Coll = mongoose.model("collectible");
var Img = mongoose.model("image");
module.exports.collectiblesList = function (req, res) {
var firstImage_ids = [];
var imageDir = "https://s3.amazonaws.com/xxxxxxxxxxx/images/";
var defaultImage = imageDir + "default.jpg";
// get the collectibles
Coll.find(req.body).exec(function (err, collectibles) {
if (!collectibles) {
// not found
sendJsonResponse(res, 404, {"message": "no collectibles found"});
return;
}
if (err) {
console.log(collectible);
sendJsonResponse(res, 400, err);
return;
}
//found the collectibles
// now find the list of images we need to pull (each collectible can have multiple images
collectibles.forEach(function (collectible, index) {
if (collectible.image_ids) {
firstImage_ids.push(collectible.image_ids[0]);
collectibles[index].imageUrl = defaultImage; // this is the line that has no effect.
collectible.imageUrl = defaultImage; // tried this too.
collectible["imageUrl"] = defaultImage; // and this. :-(
console.log(collectible);
}
});
sendJsonResponse(res, 200, collectibles);
});
};
使用 Postman 测试此 API。这就是返回的内容:
[
{
"_id": "5a43c61134aaea2025158cab",
"name": "A-0_5",
"title": "Occoneechee Lodge 104: A-0_5",
"issueDate": null,
"quantity": null,
"event_id": null,
"type": "A - Arrowhead patches",
"tag_ids": [
"5a401a17b720186ab61c649e"
],
"description": "Elangomat, no name",
"organisation_id": "5a413340b720186ab61c661e",
"supercedes_id": null,
"sortName": "A-000.5",
"image_ids": [
"5a41685ab720186ab61c663d"
],
"deleted": false,
"schemaVersion": "1.0"
},
{
"_id": "5a43c63334aaea2025158cac",
"name": "A-1",
"title": "Occoneechee Lodge 104: A-1",
"issueDate": null,
"quantity": null,
"event_id": null,
"type": "A - Arrowhead patches",
"tag_ids": [
"5a401a17b720186ab61c649e"
],
"description": "Service",
"organisation_id": "5a413340b720186ab61c661e",
"supercedes_id": null,
"sortName": "A-001",
"image_ids": [
"5a41685ab720186ab61c663e"
],
"deleted": false,
"schemaVersion": "1.0"
}]
即它不包含 imageUrl 键。
感谢您的帮助。
万维网 GT
【问题讨论】:
-
我不能直接说出为什么这不起作用,但我认为这可能与修改猫鼬响应有关。您可以尝试使用 collectibles.map(...) 的不可变方法。
标签: javascript node.js