0
我有一個適用於這些文檔的API,但我無法獲得子文檔在其中工作。Mongoose和Express子文檔API
這裏是路由器:
router.get('/locations/:locationid/reviews/:reviewid', ctrlReviews.reviewsReadOne);
這裏是控制器:
module.exports.reviewsReadOne = function(req, res) {
console.log("getting single review");
// error trap 1: check that locationid exists in request parameters
if (req.params && req.params.locationid) {
Loc
.findById(req.params.locationid)
.select('name reviews')
.exec(
function(err, location) {
var response, review;
// error trap 2: if mongoose doesn't return a location, send 404 message and exit function scope using return statement
if (!location) {
sendJsonResponse(res, 404, {
"message": "locationid not found"
});
return;
// error trap 3: if mongoose returned an error, send it as 404 response and exit controller using return statement
} else if (err) {
sendJsonResponse(res, 404, err);
return;
}
// check that returned location has reviews
if (location.reviews && location.reviews.length > 0) {
// use mongoose subdocument .id method as a helper for searching for matching ID
review = location.reviews.id(req.params.reviewid);
// if review isn't found return an appropriate response
if (!review) {
sendJsonResponse(res, 404, {
"message": "reviewid not found"
});
// if review is found build response object returning review and location name and ID
} else {
response = {
location: {
name: location.name,
id: req.params.locationid
},
review: review
};
sendJsonResponse(res, 200, response);
}
// if no reviews are found return an appropriate error message
} else {
sendJsonResponse(res, 404, {
"message": "No reviews found"
});
}
});
// if request parameters didn't include locationid, send appropriate 404 response
} else {
sendJsonResponse(res, 404, {
"message": "No reviews found"
});
}
};
文檔/子文檔我試圖進入API是this。文檔本身在API中工作良好,但我無法得到這個子文檔。如果我提供reviewid,則得到的錯誤是它找不到審閱ID。
** ------編輯------ ** 我沒有正確地將子文檔推送到文檔中。這是推動一個子文檔都有自己的ID字段到文檔中的正確方法:
db.locations.update({
"name" : "Starcups",
}, {
$push: {
'reviews' : {
author: 'kyle riggen1',
_id: new ObjectId(),
rating: 4,
timestamp: new Date("Jun 1, 2015"),
reviewText: "will the ID work?",
}
}
});
我只是缺少下劃線「_id:」
的可能的複製[檢索只在查詢的元素在MongoDB集合中的對象數組](http://stackoverflow.com/questions/3985214/retrieve-only-the-queried-element-in-an-object-array-in-mongodb-collection) –
這意味着你的代碼是真正跳過箍環來做一些MongoDB本身處理的事情。如果你只是想要一個特定的「reviewid」數組條目,那麼只需要在響應中要求匹配的元素。 –