【发布时间】:2013-09-23 22:32:52
【问题描述】:
我第一次尝试用 Angular + express + mongodb 构建一些东西,所以我可能会完全错误地处理这个问题。 Express 被用来提供 json。然后 Angular 会处理所有视图等。
我正在使用 Mongoose 与 Mongo 交互。
我有以下数据库架构:
var categorySchema = new mongoose.Schema({
title: String, // this is the Category title
retailers : [
{
title: String, // this is the retailer title
data: { // this is the retailers Data
strapLine: String,
img: String , // this is the retailer's image
intro: String,
website: String,
address: String,
tel: String,
email: String
}
}
]
});
var Category = mongoose.model('Category', categorySchema);
在 Express 中,我有几条获取数据的途径:
app.get('/data/categories', function(req, res) {
// Find all Categories.
Category.find(function(err, data) {
if (err) return console.error(err);
res.json(data)
});
});
// return a list of retailers belonging to the category
app.get('/data/retailer_list/:category', function(req, res) {
//pass in the category param (the unique ID), and use that to do our retailer lookup
Category.findOne({ _id: req.params.category }, function(err, data) {
if (err) return console.error(err);
res.json(data)
});
});
以上方法有效 - 我只是在尝试与单一零售商联系时遇到了大问题。我正在传递类别和零售商ID...我已经尝试了各种各样的事情-从对类别进行查找,然后对其中的内容进行findOne...但我就是无法让它工作。我可能会搞错这一切......
我在这里找到了这个帖子:findOne Subdocument in Mongoose 并实施了解决方案 - 但是,它返回了我所有的零售商 - 而不仅仅是我想要的那个。
// Returns a single retailer
app.get('/data/retailer_detail/:category/:id', function(req, res) {
//pass in the category param (the unique ID), and use that to do our retailer lookup
Category.findOne({_id: req.params.category , 'retailers.$': 1}, function(err, data) {
console.log(data);
if (err) return console.error(err);
res.json(data)
});
});
谢谢, 抢
【问题讨论】:
-
要使用投影运算符
$,您还需要查询数组中的某些内容。 docs.mongodb.org/manual/reference/projection/positional/… -
您是如何将范围缩小到一家零售商的?
-
感谢您的回复 :) 我通过 app.get 传入 :category - 所以: app.get('/data/retailer_detail/:category/:id', function(req , res) {.... 我正在尝试查找 - 找到类别文档,然后在其中搜索单个零售商
-
您为什么没有将零售商的搜索作为查询的一部分添加到
findOne? -
呵呵 - 好点 :) '因为我' 真的不知道我在做什么。我已经更新了上面的最后一个代码块来做到这一点 - 但我仍然无法让它工作 - 它只是注销“null”
标签: node.js mongodb angularjs mongoose