问题
EDIT: Since I wasn't able to find a correct solution, I changed the application's structure a bit and posted another question: Mongoose - find documents not in a list
I have a MEAN app with three models: User
, Task
, and for keeping track of which task is assigned to which user I have UserTask
, which looks like this:
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);
In my frontend app I have AngularJS services and I already have functions for getting all users, all tasks, and tasks which are assigned to a particular user (by getting all UserTasks
with given userId
. For example:
// 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;
});
}
Then I'm using this data in my controllers like this:
userTaskService
.getAllUserTasksForUser($routeParams.id)
.then(data => (vm.userTasks = data));
...and because of autopopulate
plugin I have complete User
and Task
objects inside the UserTasks
that I get. So far, so good.
Now I need to get all Task
s which are not assigned to a particular User
. I guess I should first get all Task
s, then all UserTasks
for a given userId
, and then make some kind of difference, with some "where-not-in" kind of filter.
I'm still a newbie for all the MEAN components, I'm not familiar with all those then()
s and promises and stuff... and I'm really not sure how to do this. I tried using multiple then()
s but with no success. Can anyone give me a hint?
回答1:
You can do at server/API side that will more efficient.
In client side, if you want to do then try below
var userid = $routeParams.id;
userTaskService
.getAllTasks()
.then((data) => {
vm.userTasks = data.filter(task => task.userId !== userid)
});
来源:https://stackoverflow.com/questions/51416648/comparing-results-from-two-api-calls-and-returning-their-difference-in-mean-app