首页 > 解决方案 > 比较两个 API 调用的结果并在 MEAN 应用程序中返回它们的差异

问题描述

编辑:由于我找不到正确的解决方案,我稍微更改了应用程序的结构并发布了另一个问题: Mongoose - 查找不在列表中的文档

我有一个包含三个模型的 MEAN 应用程序:UserTask和用于跟踪分配给我拥有的用户的任务UserTask,如下所示:

const mongoose = require("mongoose");
const autopopulate = require("mongoose-autopopulate");

const UserTaskSchema = mongoose.Schema({
  completed: { type: Boolean, default: false },
  userId: {
    type: mongoose.Schema.Types.ObjectId,
    ref: "User",
    autopopulate: true
  },
  taskId: {
    type: mongoose.Schema.Types.ObjectId,
    ref: "Task",
    autopopulate: true
  }      
});
UserTaskSchema.plugin(autopopulate);

module.exports = mongoose.model("UserTask", UserTaskSchema);

在我的前端应用程序中,我有 AngularJS 服务,并且我已经具有获取所有用户、所有任务和分配给特定用户的任务的功能(通过UserTasks使用 given获取所有内容userId。例如:

// user-task.service.js
function getAllUserTasksForUser(userId) {
  return $http
    .get("http://localhost:3333/userTasks/byUserId/" + userId)
    .then(function(response) {
      return response.data;
    });
}

// task-service.js
function getAllTasks() {
  return $http.get("http://localhost:3333/tasks").then(function(response) {
    return response.data;
  });
}

然后我在我的控制器中使用这些数据,如下所示:

userTaskService
    .getAllUserTasksForUser($routeParams.id)
    .then(data => (vm.userTasks = data));

...并且由于autopopulate插件,我得到了完整UserTask对象UserTasks。到目前为止,一切都很好。

现在我需要获取所有Task未分配给特定. 我想我应该首先获取所有s,然后获取所有给定的,然后使用某种“where-not-in”过滤器做出某种差异。UserTaskUserTasksuserId

我仍然是所有 MEAN 组件的新手,我不熟悉所有这些then()s 和 promises 和东西......而且我真的不知道该怎么做。我尝试使用多个then()s 但没有成功。谁能给我一个提示?

标签: angularjsmongoosemean

解决方案


您可以在服务器/API 端进行更高效的操作。

在客户端,如果你想做,那么试试下面

var userid = $routeParams.id;
userTaskService
    .getAllTasks()
    .then((data) => {
        vm.userTasks = data.filter(task => task.userId !== userid)
    });

推荐阅读