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

查看:48
本文介绍了如何查询 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:

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

我想在 API 中编写一个查询,查询一个提供者的所有帖子.这个 router.get 不工作并给我错误的答案.请如果有人可以帮助我更改此查询以更正一个.我将不胜感激.

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.

推荐答案

给定您的架构和路由,我假设您有一个名为 Provider 的模型,它使用显示的架构并且 :provider 是所请求提供程序的 ID.如果是这样,您可以使用 findById.此外,由于您使用的是引用数组,因此您需要 populate 如果你想要他们的 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);
  });
});

否则,如果您尝试使用 Post 模型,则需要显示该架构.

Otherwise if you are trying to use the Post model you need to show that schema.

更新:使用您的 Post 模型:

UPDATE: Using your Post model:

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天全站免登陆