如何查询API来获取路径的第三级中的所有数据? [英] How query API to get all the data for third level of path?

查看:130
本文介绍了如何查询API来获取路径的第三级中的所有数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是当前模式,我有:

var Schema = mongoose.Schema;

    var ProviderSchema = new Schema({
        name: String,
        abbreviated: String,
        services: Array,
        locations: Array,
        description: String,
        url: String,
        upvotes:{type:Number, default:0},
        createdOn: { type: Date, default: Date.now},
        posts:[{ type: mongoose.Schema.Types.ObjectId, ref: 'Post' }]
    });

这是后模式:

var PostSchema = new mongoose.Schema({
     title: String,
     body: String,
     upvotes: {type: Number, default:0},
     author: String,
     provider: { type: mongoose.Schema.Types.ObjectId, ref: 'Provider' },
     comments:[{ type: mongoose.Schema.Types.ObjectId, ref: 'Comment' }]
 });

我填充后前:

router.get('/providers/:provider', function(req, res) {
    req.provider.populate('posts', function(err, provider) {
        res.json(provider);
    });
});

而这正是我在我的API:

And this is what i have in my API:

router.get('/providers/:provider/posts', function(req, res) {
    Post.find(function(err, post){
        if(err){ return next(err); }
        res.json(post);
    });
});

我想编写API查询该查询所有职位的一个供应商。这router.get不工作,并给回我错了answer.Please如果有人可以帮助我改变这个查询正确的。我将AP preciated。

I would like to write a query in API which query all the posts for one provider. This router.get is not working and give back me wrong answer.Please if somebody can help me to change this query to correct one. I will be appreciated.

推荐答案

由于您的架构和路线我假设你有一个名为提供模式,使用显示的模式和:供应商中的URL请求的提供商ID。如果是这样,你可以使用 findById 。此外,由于使用的是引用数组,你需要 填充 他们,如果你想比自己的ID以外的其他:

Given your schema and route I assume you have a model called Provider that uses the schema shown and that :provider in the URL is the ID for the requested provider. If so you could use findById. Also, since you are using an array of references you will need to populate them if you want anything other than their IDs:

router.get('/providers/:provider/posts', function(req, res) {
  Provider.findById(req.params.provider).select('posts').populate('posts').exec(function(err, provider) {
    if(err){ return next(err); }
    res.json(provider.posts);
  });
});

否则,如果你要使用你需要证明架构发表模式。

更新:使用你的发表模型:

router.get('/providers/:provider/posts', function(req, res) {
  Post.find({provider: req.params.provider}, function(err, posts) {
    if(err){ return next(err); }
    res.json(posts);
  });
});

这篇关于如何查询API来获取路径的第三级中的所有数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆