[英]Searching a nested json from Node.js applictaion by id
我的JSON文件如下,我的路由器router.get('/ books /:bookid',ctrlbooks.booksReadOne); 返回以下JSON,這是預期的,但如果我想返回只有這個api的標題,給定id router.get('/ books /:bookid / titles /:titleid',ctrlbooks.titlesReadOne); 它不會工作我錯過了什么?
[
{
"_id": "58dd21c3cb77090b930b6063",
"bookAuthor": "George Orwell",
"titles": [
{
"title": "Animal Farm",
"_id": "58dd3f2701cc081056135dae",
"reviews": [
{
"author": "Lisa",
"rating": 4,
"reviewText": "this is a review",
"_id": "58dd8e13876c0f16b17cd7dc",
"createdOn": "2017-03-30T23:00:35.662Z"
}
],
"favouredBy": [
"bb, aa, cc"
]
},
{
"title": "1984",
"_id": "58dd42a59f12f110d1756f08",
"reviews": [
{
"author": "jessy",
"rating": 5,
"reviewText": "REVIEW FOR SECOND TITLE",
"_id": "58dd8ef46d4aaa16e4545c76",
"createdOn": "2017-03-30T23:04:20.609Z"
}
],
"favouredBy": [
"all"
]
}
]
}
]
我的路由器router.get控制器('/ books /:bookid',ctrlbooks.booksReadOne); 是
module.exports.booksReadOne = function(req, res) {
console.log('Finding book details', req.params);
if (req.params && req.params.bookid) {
Bok
.findById(req.params.bookid)
.exec(function(err, book) {
if (!book) {
sendJSONresponse(res, 404, {
"message": "bookid not found"
});
return;
} else if (err) {
console.log(err);
sendJSONresponse(res, 404, err);
return;
}
console.log(book);
sendJSONresponse(res, 200, book);
});
} else {
console.log('No bookid specified');
sendJSONresponse(res, 404, {
"message": "No bookid in request"
});
}
};
這就是我試圖只提供給定標題ID的標題,但是當我使用郵遞員測試它時這不起作用
module.exports.tilesReadOne = function(req, res) {
console.log('Finding book details', req.params);
if (req.params && req.params.titleid) {
Bok
.findById(req.params.titleid)
.exec(function(err, book) {
if (!book) {
sendJSONresponse(res, 404, {
"message": "title not found"
});
return;
} else if (err) {
console.log(err);
sendJSONresponse(res, 404, err);
return;
}
console.log(book);
sendJSONresponse(res, 200, book);
});
} else {
console.log('No title specified');
sendJSONresponse(res, 404, {
"message": "No title in request"
});
}
};
除了聚合,您可以在應用程序級別篩選標題:
Bok
.findById(req.params.bookid)
.exec(function(err, book) {
if (book) {
var matchingTitles = book.titles.filter(function(title){
return title._id == req.params.bookid
})
// return titles, if any
}
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.