我跟随着这本书"获得意义"然而,作者Simon Holmes,我偶然发现了一个关于子文档ID的问题。我正在尝试申请"审核文件"在"位置文档"使用mongoose docs提供的" MongooseDocumentArray.id(id)帮助函数。但是,我的所有子文档都会生成" id"但前面提到的功能需要" _id"而是返回" null"对象
功能描述:使用匹配的_id搜索第一个文档的数组项。
这是什么问题?我的父文件是"位置"使用" _id"生成其id,这让我更加困惑......嵌套的架构设置,包含审阅子文档的数据库中返回的位置对象以及执行查询的路由的控制器函数分别在以下代码片段中。
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);
}
}
})
}
};
答案 0 :(得分:0)
将架构更改为以下内容。
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: [{
author: String,
rating: {type: Number, required: true, min: 0, max: 5},
reviewText: String,
createdOn: {type: Date, "default": Date.now
}]
});
答案 1 :(得分:0)
实际上我正在读这本书,这本书很精彩,提供了很多关于MEAN堆栈的简单和优化架构的信息,问题出在本书的代码中使用时:
$ push:{reviews:{author:'Simon Holmes', id:Objectid(),...
此代码中的使用 id 而不是 _id ,因此正确的脚本为:
db.locations.update({name:'Starcups'},{$ push:{reviews:{author:'Simon Holmes', _id:ObjectId(),评分: 5,时间戳:新日期(“2013年7月16日”),reviewText:“多么好的地方。我不能说它很好”}}}});
“通过Mongo shell添加新的子文档时,您需要将id指定为_id。”(Holmes S.) https://forums.manning.com/posts/list/35152.page