Loc
.findById(req.params.locationid)
.select('name reviews')
.exec(
function(err, location) {
if (location.reviews && location.reviews.length > 0) {
// this is the problem:
review = location.reviews.id(req.params.reviewid);
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);
}
}
}
);
id
不是函数,因此id()
不返回任何内容。
我努力编码id编号,厌倦了我在网上找到的很多东西,但最重要的是location.reviews.id
只是一个值。我也做了Loc.findById(req.params.locationid).reviews ...
:where
,findById
,没有!我也花了很多时间尝试_id
和许多与之相关的事情
如果reviews.id
匹配,我可以遍历评论并停止,但我想知道作者试图做什么。
我理解的方式是location
是一个javascript对象,自然不能将id
用作函数
这是架构
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'},
openingTimes: [openingTimeSchema], //nesting a schema
reviews: [reviewSchema]
});
整个模块代码是(虽然我没有分享它,但我没有选择正确的块):
module.exports.reviewsReadOne = function(req, res) {
console.log("Getting single review");
if (req.params && req.params.locationid && req.params.reviewid) {
Loc
.findById(req.params.locationid)
.select('name reviews')
.exec(
function(err, location) {
if (location.reviews && location.reviews.length > 0) {
review = location.reviews.id(req.params.reviewid);
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);
}
}
}
);
} else {
sendJSONresponse(res, 404, {
"message": "Not found, locationid and reviewid are both required"
});
}
};
比你帮忙吗?
答案 0 :(得分:1)
根据我们的讨论,我们找到了
的根本原因db.locations.update({ name: 'Starcups' },
{ $push: {
reviews: {
author: 'Simon Holmes',
id: ObjectId(), // issue is here
rating: 5, ... } } })
id: ObjectId()
将在子文档中创建id
字段,而_id
子文档中没有reviews
字段。
id()
方法用于documentArrays有一个特殊的id
方法,用于通过_id
查找文档。由于_id
文档数组中没有reviews
字段,因此效果不佳。
请从代码中删除id: ObjectId()
。