[英]How to find the document by custom field name (not _id) in the mongodb using nodejs?
I have documents in my mongodb like this 我的mongodb中有这样的文件
{
"song_Name": "akon-Breakdown",
"album_Name": "Akon collection",
"release_date": "2019-09-11T18:30:00.000Z",
"description": "akon popular collection",
"song_image_uri": "http://neptechco.com/assets/akon-breakdown.jpg",
"song_uri": "https://monal.s3-us-west-2.amazonaws.com/Audio/English/collection/akon-Breakdown.mp3",
"home_featured": true,
"_id": "5d7980c1d043b70dfd2dcfc5",
"song_main_category": "English"
"__v": 0
}
Now i am creating an API for finding the song by its song_uri not by its id to check if there is any duplicate song posted. 现在,我正在创建一个API,用于根据song_uri而不是其ID查找歌曲,以检查是否发布了重复的歌曲。
But i think this is going to be so complex. 但是我认为这将是如此复杂。
If there is any other suggestion to find the song by its song_uri, I would really appreciate the suggestions. 如果还有其他建议可以通过song_uri找到这首歌,我将不胜感激。
I can do it by finding by id and searching its song_uri in findall API 我可以通过id查找并在findall API中搜索它的song_uri来做到这一点
here is my code how i am trying 这是我正在尝试的代码
let getMusicInfo = (req, res) => {
const songurl = req.params.songId;
Music.find({ _id: songurl })
.exec()
.then(result => {
if (result.length > 0) {
let currentSongURL = result.song_uri;
Music.find()
.exec()
.then(docs => {
for (let i = 0; i < docs.length; i++) {
if (currentSongURL == docs[i].song_uri) {
console.log("duplicate")
} else {
res.status(200).json(result);
}
}
})
.catch(err => {
res.status(500).json({
error: err
});
})
}
})
}
I expect the output to send me duplicate message when the song_uri is already present in any of the document in mogodb. 我希望在mogodb中任何文档中都存在song_uri时,输出将向我发送重复消息。
If you can pass song_uri
in query param of GET, as you're not able to make it POST api(ideally url can be passed as string in post request body & be retrieved as req.body.songURL
, url in path param of GET is not that feasible) - So if considering query param then you don't need to make two find calls to DB - Once you get the result of .find() if you get more than one record then that song_uri
has duplicate records in DB (We're doing exact match for a string, not a partial search & also if this happens often try to have an index on the field & make that text field as text index), Below is sample code - Please try this : 如果您可以在GET的查询参数中传递
song_uri
,则因为您无法使其成为POST api(理想情况下,URL可以在请求请求正文中作为字符串传递,并可以作为req.body.songURL
检索,在GET的参数中为url不太可行)-因此,如果考虑查询参数,则无需对DB进行两次查找-一旦获得.find()的结果(如果获得多个记录),则song_uri
在DB song_uri
有重复的记录(我们正在对字符串进行完全匹配,而不是部分搜索;如果发生这种情况,通常会尝试在字段上建立索引并将该文本字段作为文本索引),下面是示例代码-请尝试以下操作:
let getMusicInfo = (req, res) => {
//const songurl = req.params.songId;
// let's say you get song_uri in songURL
Music.find({ song_uri: req.query.songURL })
.exec()
.then(result => {
if (result.length > 1) {
console.log("duplicate")
res.status(409);
} else {
res.status(200).json(result);
}
}).catch(err => {
res.status(500).json({
error: err
});
})
}
else if you don't have song_uri
value & only have _id
of a song & still need to find duplicates on song_uri
(no change in your requirement) then try this, this helps to avoid two DB calls, check on performance of this query : 否则,如果您没有
song_uri
值且仅具有歌曲的_id
且仍需要在song_uri
上找到重复song_uri
(您的要求没有任何变化),请尝试执行此操作,这有助于避免两次数据库调用,请检查此查询的性能:
let getMusicInfo = (req, res) => {
const songID = req.params.songId;
Music.aggregate([{ $project: { song_uri: 1 } },
{ $group: { _id: '$song_uri', doc: { $push: '$$ROOT' } } },
{ $match: { 'doc._id': songID } },
{ $project: { songUrlsCount: { $size: '$doc' } } }])
.exec()
.then(result => {
if (result.length && result.songUrlsCount > 1) {
console.log("duplicate")
res.status(409);
} else {
res.status(200).json(result);
}
}).catch(err => {
res.status(500).json({
error: err
});
})
} }
Or by doing two DB calls(Only change below is instead doing .find() on entire collection & iterating changed to specific thing ie; _id, no change in your requirement) : 或者通过执行两次数据库调用(仅以下更改是对整个集合执行.find()并迭代更改为特定内容,即_id,您的要求没有更改):
let getMusicInfo = (req, res) => {
const songurl = req.params.songId;
Music.find({ _id: songurl })
.exec()
.then(result => {
if (result.length > 0) {
let currentSongURL = result.song_uri;
Music.find({ song_uri: currentSongURL })
.exec()
.then(result => {
if (result.length > 1) {
console.log("duplicate")
res.status(409);
} else {
res.status(200).json(result);
}
}).catch(err => {
res.status(500).json({
error: err
});
})
}
}).catch(err => {
res.status(500).json({
error: err
});
})
}
Please consider this as basic structure, Refactor & think through error scenarios as well.. 请将此视为基本结构,并重构并仔细考虑错误情况。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.