无法访问我的节点中的特定值.js猫鼬模型(仅对象)



我已经在这方面工作了4个小时。因此,我希望得到一些帮助。我想访问数据库中的特定值,例如response.data.values.imglink,尽管当在console.log()中添加imglink时,我得到了undefined。我可以得到一般对象,但不能得到specifik值。

我已将我的歌曲模式定义为:

const songSchema = new Schema({
values: [{
imglink: {
type: String
},
id: {
type: String
},
spotify: {
type: String,
},
soundCloud: {
type: String,
},
youtube: {
type: String,
},
appleMusic: {
type: String,
}}
],
}, {
timestamps: true,
})

正如您所看到的,values是一个对象数组。这里有类似问题的人没有在他们的Schema中包含正确的值,所以这可能是我的问题?虽然在我看来是正确的。然后我获取数据库中的值。JSON对象通常看起来像这样:

[
{
"_id": "5ffbba4dc47e847a79c9c68f",
"values": [
{
"_id": "5ffbba4dc47e847a79c9c690",
"imglink": "imagelink",
"id": "id",
"soundCloud": "soundcloudvalue",
"youtube": "youtubevalue",
"appleMusic": "applemusicvalue",
"spotify": "spotifyvalue"
}
]
}
]

我用这个函数来调用它,它应该打印出单个值:

const getAllSongs = () => {
axios.get('http://localhost:5000/songs/'+id)
.then(function (response) {
console.log(response); // returns an object
console.log(response.data.values.imglink); // returns an object  
})
.catch(function (error) {
// handle error
console.log(error);
})
}

我有一个Express路由对象,它允许我在VS代码HTTP客户端(类似于邮递员(中通过其idGET http://localhost:5000/songs/id访问歌曲:

router.get(`/:id`, function(req, res) {
return Song.find(
{"values.id": req.params.id}
).then(function(song) { 
// return orders when resolved
res.send(song);
console.log(id);
res.json('works yesss');
})
.catch(function (err) {
// handle error
res.status(400).json('Error: '+err)
})
});

以下是我尝试过的一些流行的解决方案:

用JSON.stringify((封装响应不起作用。

toObject((和toJSON((也不起作用,因为我使用它们时没有定义它们。dochack也不起作用。

我试着查看了Schema,我认为这就是问题所在。POST请求添加了正确的数据,GET请求通过了,我只是无法访问特定的值。

我希望你有时间帮忙,谢谢。我将不胜感激。当然,如果你有任何问题,请告诉我。

find((的结果是一个Array,所以访问所需的键,如果结果Array的长度为1,则访问所需键是response.data[0].values[0].imglink

注意values密钥是obejct 的array

如果数组大小大于1,则要查看结果,可以使用map()如果不起作用,请使用类似的lean((

router.get(`/:id`, function(req, res) {
return Song.find(
{"values.id": req.params.id}
).lean().then(function(song) { 
// return orders when resolved
res.send(song);
console.log(song[0].values[0].imglink); // type of song is array of object [] and values is array
res.json('works yesss');
})
.catch(function (err) {
// handle error
res.status(400).json('Error: '+err)
})
});

最新更新