0
我跟着Simon Holmes的書「Getting MeAN」一書,但是,我偶然發現了有關子文檔的問題IDS。我試圖使用「貓鼬」提供的幫助函數「MongooseDocumentArray.id(id)」在「位置文檔」中請求「審閱文檔」。但是,我的所有子文檔生成「id」,但前面提到的函數需要「_id」,因此返回「空「對象Mongoose:我需要子文檔來生成「_id」而不是「id」來搜索文檔數組
功能描述:?搜索與匹配_id的第一個文檔數組項
問題是什麼在這裏,我父文檔是‘位置_id’與產生它的ID」 「,這讓我更加困惑......嵌套的模式設置,從包含審閱子文檔和控制器功能的數據庫返回的位置對象fo查詢的路由分別在下面的代碼片段中說明。
var mongoose = require("mongoose");
var reviewSchema = new mongoose.Schema({
author: String,
rating: {type: Number, required: true, min: 0, max: 5},
reviewText: String,
createdOn: {type: Date, "default": Date.now}
});
var locationSchema = new mongoose.Schema({
name: {type: String, required: true},
address: String,
rating: {type: Number, "default": 0, min: 0, max: 5},
facilities: [String],
coords: {type: [Number], index: "2dsphere"},
reviews: [reviewSchema]
});
mongoose.model('Location', locationSchema);
Returned Location object showing subdocuments containing id instead of _id
對於下面的片段,這是相關的路線:
router.get("/locations/:locationid/reviews/:reviewid", ctrlReviews.reviewsReadOne);
module.exports.reviewsReadOne = function(req, res){
if(req.params && req.params.locationid && req.params.reviewid){
Loc.findById(req.params.locationid)
.select("name reviews")
.exec(function(err, location) {
var response, review;
if(location.reviews && location.reviews.length > 0){
// This returns zero, because the function requires _id
// but all subdocuments have path/properties called id
review = location.reviews.id(req.params.reviewid);
console.log(review);
if(!review){
sendJsonResponse(res, 404, {
"message": "reviewid not found"
});
} else {
response = {
location: {
name: location.name,
id : req.params.locationid
},
review: review
};
sendJsonResponse(res, 200, response);
}
}
})
}
};
只要我設法修復我的數據庫連接,在完整系統重新安裝後有一些問題重新連接,我會立即檢查此解決方案。 – Peyno
它不工作。我仍然遇到同樣的問題。任何其他想法將不勝感激,謝謝 – Peyno