我有一个模型Player
,其中包含slug
字符串,name
字符串和nickname
数组。在昵称数组中,我将存储nickname
个模型。我创建了一个带有名称和slug的玩家,然后我逐个创建每个nickname
模型并将它们推送到player.nickname
。然后我保存player
并将其作为回调结果返回。
当我将它打印到控制台时,就像这样:
{ name: 'Max Zaslofsky',
nickname: ["{ _id: 56a35c2b33a41a8c187efd08, nickname: 'Slats', __v: 0 }"] }
然后我尝试打印它的名字及其昵称:
let player = results.findRandomPlayer;
let nicknames = player.player_nickname;
console.log("Player is", player.name);
console.log("His nickname is:");
_.forEach(nicknames, function (nickname) {
console.log(nickname.nickname);
});
但它打印到控制台:
Player is Max Zaslofsky
His nickname is:
我做错了什么?
答案 0 :(得分:0)
根据您所写的内容,昵称包含一系列未解析的json对象字符串。
您的代码应如下所示:
let player = results.findRandomPlayer(); // invoke function!
let nicknames = player.nickname; // use correct propertyname
console.log("Player is", player.name);
console.log("His nickname is:");
_.forEach(nicknames, function (nickname) {
// its not an object its an unparsed object
console.log(JSON.parse(nickname).nickname);
});
答案 1 :(得分:-1)
在nickname数组中,您正在推送字符串而不是对象。删除双引号" "
,我的意思是将昵称存储为对象而不是字符串。您可以使用JSON.parse(nicknameString)
{
name: 'Max Zaslofsky',
nickname: ["{ _id: 56a35c2b33a41a8c187efd08, nickname: 'Slats', __v: 0 }"] }
应该是
{
name: 'Max Zaslofsky',
nickname: [{ _id: 56a35c2b33a41a8c187efd08, nickname: 'Slats', __v: 0 }]
}