我第一次尝试使用 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...但我就是无法让它工作。我可能对这一切都错了......
我在这里找到了这个线程:Mongoose 中的 findOne 子文档 https://stackoverflow.com/questions/13460765/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)
});
});
谢谢,
抢