我正在读一本书,代码不起作用。谷歌和这里的一切都表明该代码是正确的!没用
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"
});
}
};
比你有帮助吗?
根据我们的讨论,我们找到了根本原因
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()
从您的代码中删除。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句