Rob*_*Rob 5 mongoose mongodb node.js angularjs
我第一次尝试使用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);
Run Code Online (Sandbox Code Playgroud)
在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)
});
});
Run Code Online (Sandbox Code Playgroud)
上述工作 - 我只是在试图进入一家零售商时遇到大问题.我正在通过这个类别和零售商ID ...我已经尝试了各种各样的事情 - 从对类别进行查找,然后对内容中的findOne进行...但我不能让它工作.我可能会说这一切都错了......
我在这里找到了这个帖子:在Mongoose中查找了一个Subdocument并实现了解决方案 - 然而,它返回了我所有的零售商 - 而不仅仅是我想要的那个.
// 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)
});
});
Run Code Online (Sandbox Code Playgroud)
谢谢,罗布
现在我看到了您的完整过滤器/查询,您应该能够在这种情况下使用数组位置运算符作为投影的一部分,而不是进行客户端过滤:
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({
/* query */
_id: req.params.category ,
'retailers._id' : req.params.id
},
{ /* projection */
"retailers.$" : 1
},
function(err, data) {
var retailer = _.where(data.retailers , { id : req.params.id });
if (err) return console.error(err);
res.json(retailer)
});
});
Run Code Online (Sandbox Code Playgroud)
为了{ "retailers.$" : 1 }使其正常工作,查询必须包含数组中元素的字段.该$操作仅返回第一个匹配.