推入数组猫鼬时对象对象而不是字符串
Object object instead of string when pushing into array mongoose
我有以下插入配料的功能:
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]"
}
]
]
i 运行 不知道如何修复它,也许有人会有想法?
例如,当我在 names[i].toString 上执行 typeof 时,在推送之前它的类型为 String
您遇到此问题是因为您正试图将对象转换为字符串,因此显示了这样的字符串 "[object Object]"
。
您需要从上面评论中所说的对象中获取 ingr_name
。因此,与其将整个对象转换为字符串,不如像这样
从对象中提取 ingr_name
names->ingr_name
我有以下插入配料的功能:
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]"
}
]
]
i 运行 不知道如何修复它,也许有人会有想法? 例如,当我在 names[i].toString 上执行 typeof 时,在推送之前它的类型为 String
您遇到此问题是因为您正试图将对象转换为字符串,因此显示了这样的字符串 "[object Object]"
。
您需要从上面评论中所说的对象中获取 ingr_name
。因此,与其将整个对象转换为字符串,不如像这样
ingr_name
names->ingr_name