API NodeJS的查询和响应方式

时间:2019-07-07 02:44:08

标签: node.js mongodb

我想查询和响应API。我有2个集合“帐户”和“用户”。 “用户”具有“ id”字段,“帐户”具有“ user_id”字段-我们俩都是一个。一个“用户”拥有一个或多个帐户,并且在“帐户”集合中具有“ id”字段。我想从“用户”集合中查询“ id”,并期望该用户的结果详细信息以及其中的1个字段“ accounts_id”。

这是我所有的预期结果,如下所示: https://sample-accounts-api.herokuapp.com/

我试图收集“ accounts_id”,但我不知道如何查询并将其添加到“用户”详细信息中。

这是我收集的“ accounts_id”:

exports.findAllAccountIDforUser = (req, res) => {
    Account
    .find({user_id: req.param('user_id')})
    .then(result => {
        let a = result.map(data => {
            return data.id;
        })
        res.send({'accounts_id':a});

    })
}

我的“用户”模式:

var mongoose = require('mongoose');
mongoose.Promise = require('bluebird');
var Schema = mongoose.Schema,
    ObjectId = Schema.ObjectId;

const Account = require('../model/account');

var UserSchema = new mongoose.Schema({
        id: {type: Number, unique: true},
        name: String,
});

const User = mongoose.model('User', UserSchema);

module.exports = User;

我的“帐户”模式:

var mongoose = require('mongoose');
mongoose.Promise = require('bluebird');
var Schema = mongoose.Schema,
    ObjectId = Schema.ObjectId;

var AccountSchema = new mongoose.Schema({
        id: {type: Number},
        user_id: {type: Number, ref: 'User'},
        name: String,
        balance: Number
});


const Account = mongoose.model('Account', AccountSchema);

module.exports = Account;

2 个答案:

答案 0 :(得分:0)

使用async-await,您可以在4行中完成它。

  • 获取用户
  • 获取与该用户相关的所有帐户
  • 分配user.account_ids =帐户
  • 发送响应。

     exports.findAllAccountIDforUser = async(req, res) => {
        let user=await User.findOne({id:req.param('user_id')});
        let accounts= await Account.find({user_id: req.param('user_id')}).select(' _id id);
        user.account_ids=accounts;
        res.send(user);
       }
    

另一种方式是像已经在使用诺言一样使用诺言。

exports.findAllAccountIDforUser = (req, res) => {
 User
 .findOne({id:req.param('user_id')})
  .then(user=>{
    Account
    .find({user_id: req.param('user_id')})
    .then(result => {
        let a = result.map(data => {
            return data.id;
        })
       user.account_ids=a;
        res.send(user);

    })
})
}

答案 1 :(得分:0)

我有答案:

exports.findAlldetail = (req, res) => {
   User
   .aggregate([
       {
           $match: {
                id: +req.param('id')}
        },
       {
           $lookup: {
                from: "accounts",
                localField: "id",
                foreignField: "user_id",
                as: "account_ids"
            }
        },
       {    
            $project: {
                _id: 0,
                id: 1,
                name: 1,
                "account_ids.id": 1
            }
       }
   ])
   .then(result => {
        result.account_ids = result.map(data => {
            data.account_ids = data.account_ids.map(b => b.id);
         })
        res.send({"attributes":result});
   })
}