如何在节点js中过滤用户ID

时间:2018-03-28 03:56:17

标签: javascript node.js

我使用node.js创建了2个API,而在后端我正在使用mongodb。我的第一个API我有所有的用户名列表和另一个API我将获得单个用户ID我需要使用包含userid列表的第一个API进行过滤,如果userid匹配,那么我需要发送受尊重的id。

模式

var mongoose = require('mongoose');

var filtertripSchema = new mongoose.Schema({
    filterId : String
});

在此API中,我将收到单个用户ID

module.exports = mongoose.model('filtertrip', filtertripSchema);
const express = require('express');
const router = express.Router();
const mongoose = require('mongoose');
const filter = require('../models/filtertrip');
const expensemaster = require('../models/expensemaster.js'); //here i am call another API which contain list of userid

  router.post('/',  function(req, res, next) {
    filter.create(req.body, function (err, products) {
      if (err) return next(err);
     var Id = products.filterId;
    });
  });

包含userid列表的模式

var expensemaster = new mongoose.Schema({
    // expensecategoryname: String,
    expensecategory : {type: mongoose.Schema.Types.ObjectId, ref: 'expensecategory'},
    tripid : {type: mongoose.Schema.Types.ObjectId, ref: 'tripmaster'}
});

输出

{
        "_id": "5aba44a56bef1ea0e8817d1e",
        "expensecategory": "5ab89f17f03cfe71f065eda7"
        "tripid": {
            "usersid": [
                "5ab9e0f2a9bcd1050c2f1c92",
                "5ab9e134a9bcd1050c2f1c93",
                "5ab9e169a9bcd1050c2f1c94",
                "5ab9e1a3a9bcd1050c2f1c95",
                "5ab9e2f6a9bcd1050c2f1c97",
                "5aba037057a5b166800c13dd"
            ],
            "_id": "5aba3c9b6bef1ea0e8817d05"
        },
        "__v": 0
    },
    {
        "_id": "5aba44a56bef1ea0e8817d22", // I NEED TO SEND THIS ID IF THE USERID IS MATCHING
        "expensecategory": "5ab89f17f03cfe71f065eda7",
        "tripid": {
            "usersid": [
                "5ab9e0f2a9bcd1050c2f1c92",
                "5ab9e134a9bcd1050c2f1c93",
                "5ab9e169a9bcd1050c2f1c94",
                "5ab9e1a3a9bcd1050c2f1c95",
                "5ab9e2f6a9bcd1050c2f1c97",
                "5aba037057a5b166800c13dd"
            ],
            "_id": "5aba3c9b6bef1ea0e8817d05"
        },
        "__v": 0
    }

当我从Another Api获取用户ID时,我需要调用它并过滤并发送_id

请帮助我,我是node.js的新手

1 个答案:

答案 0 :(得分:0)

您应该使用middlewares。在您的第一个API中,用于获取userIds传递控制到另一个middleware,它将过滤ID并最终发回响应。

  

https://expressjs.com/en/guide/using-middleware.html

了解有关快速中间件的更多信息