【问题标题】:Object object instead of string when pushing into array mongoose推入数组猫鼬时对象对象而不是字符串
【发布时间】:2018-02-21 12:49:39
【问题描述】:

我有以下添加成分的功能:

router.post('/api/recipes/ingredient/post', function (req, res) {
    console.log('before for');
    var names = req.body.ing_name;
    var amounts = req.body.ing_amount;
    for (var i = 0; i < names.length; i++) {
        var ingredientItem = {ingredient_name: names[i].toString(), amount: amounts[i].toString()};
        Recipe.update({name: req.body.name},
            {$push: {"ingredients": ingredientItem}},
            function (err, res) {
                if (err) {
                    console.log(err)
                    console.log("ERROR OCCURRED, COULD NOT SAVE USER IN DATABASE");
                }
                else {
                    console.log("USER SUCCESSFULLY MODIFIED IN DATABASE");
                }
            });
    }
});

但在收藏中它最终是:

"ingredients" : [ 
        [ 
            {
                "_id" : ObjectId("59b8726b4de01a2958511871"),
                "amount" : "[object Object]",
                "ingredient_name" : "[object Object]"
            }
        ], 
        [ 
            {
                "_id" : ObjectId("59b8726b4de01a2958511872"),
                "amount" : "[object Object]",
                "ingredient_name" : "[object Object]"
            }
        ]
    ]

我没有办法解决它,也许有人会有想法? 例如,当我在 names[i].toString 上执行 typeof 时,在推送它的类型为 String

【问题讨论】:

  • 控制台日志names[i].toString()会得到什么
  • 那个对象 Object thingy 现在对我来说更没有意义了
  • 那么这不是插入问题,问题出在其他地方。现在请控制台日志name[i] 并粘贴它的结果,以便我可以看到正在转换为字符串的内容
  • {ingr_name: 'bleble'} 但为什么呢?
  • 您正在将对象转换为字符串,因此显示"[object Object]"

标签: arrays node.js mongodb mongoose mean-stack


【解决方案1】:

您正面临这个问题,因为您试图将一个对象转换为字符串,因为这样的字符串显示"[object Object]"

您需要从对象中获取ingr_name,正如您在上面的 cmets 中所说的那样。因此,与其将整个对象转换为字符串,不如像这样从对象中提取ingr_name

names-&gt;ingr_name

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-09-13
    • 1970-01-01
    • 1970-01-01
    • 2022-01-07
    • 2018-07-12
    • 2012-08-26
    • 2015-12-28
    • 2021-05-06
    相关资源
    最近更新 更多