【发布时间】:2018-02-09 19:46:14
【问题描述】:
我正在关注 Simon Holmes 的“Getting MEAN”一书,但是,我偶然发现了一个关于子文档 ID 的问题。我正在尝试使用猫鼬文档提供的“MongooseDocumentArray.id(id) helper 函数在“位置文档”中请求“审阅文档”。但是,我的所有子文档都生成“id”,但前面提到的函数需要“_id”返回“空”对象。
功能说明:在数组项中搜索第一个与_id匹配的文档。
这里有什么问题?我的父文档是“位置”,它使用“_id”生成它的 id,这让我更加困惑......嵌套模式设置,从包含审查子文档的数据库中返回的位置对象以及执行查询的路由的控制器函数分别在下面的代码 sn-ps 中说明。
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
对于下面的sn-p,这是相关的路由:
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);
}
}
})
}
};
【问题讨论】: