【问题标题】:Failing to add a key and value to a javascript object无法向 javascript 对象添加键和值
【发布时间】: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


【解决方案1】:

我可能误会了。但是,如果您的问题是 collectibles[i].imageUrl 稍后返回 undefined/null,那么我相信这仅仅是因为您需要添加

collectibles.save();

在设置 collectibles[i].imageUrl 值之后。您可以在 foreach 循环之后、json 响应之前添加该行。

collectibles.forEach(function (collectible, index) {
    if (collectible.image_ids) {
        firstImage_ids.push(collectible.image_ids[0]);
        collectible.imageUrl = defaultImage;
    }
});
collectibles.save(); //here, this saves the changes done to the mongoose object.
sendJsonResponse(res, 200, collectibles);

【讨论】:

  • 我不打算更新 mongoDB 中的数据,只需将 ImageURL 添加到通过 RESTful API 返回的收藏品中。猫鼬.save() 。我认为这就是 collectible.save() 的作用?
  • 哦,所以值一开始就没有改变?在这种情况下,首先要确保 if (collectible.image_ids) 语句首先被传递,方法是在任何其他代码之前在其中添加一个 console.log。如果 if 语句确实通过了。那么你的问题是收藏品本身。您是否可能没有在您的收藏模式中定义属性 imageUrl ?因为据我所知,猫鼬不允许添加未知属性——那些未在架构中定义的属性
  • 我解决了这个问题 - 花费了很多精力,我想出了两种解决方法。我要添加的对象并不是它看起来的全部。本文解释(但我还没有完全按照解释)stackoverflow.com/questions/18821212/mongoose-whats-up-with-doc
【解决方案2】:

经过一番努力,我最终解决了它。 This article 解释(但我还没有完全按照解释)

我发现对象中包含更多元数据,而实际对象在 _doc 中,所以第一个(我怀疑解决方案不满意)是将代码更新为:

collectible._doc.imageUrl = defaultImage;

更好的方法是简单地将 imageUrl 添加到 mongoose 模型中并将 _doc 排除在外。那里的问题是这不是我打算在 mongoDB 中填充的字段。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-02-22
    • 2018-08-22
    • 1970-01-01
    • 2015-11-30
    • 2023-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多