Mongoose - 查找不在另一个对象列表中的对象

Mongoose - find objects which are NOT IN another list of objects

A few days ago I posted this question. Since I didn't find a working solution, I've changed my app's structure a bit and that's why I'm posting this new question.

UserTask 型号。一个 User 包含两个列表 Tasks,它们是 tasksAssignedtasksCompleted:

user.model.js

const mongoose = require("mongoose");
const autopopulate = require("mongoose-autopopulate");
const UserSchema = mongoose.Schema({
  username: String,
  password: String,
  firstName: String,
  lastName: String,
  friends: [
    { type: mongoose.Schema.ObjectId, ref: "User", autopopulate: true }
  ],
  tasksAssigned: [
    { type: mongoose.Schema.ObjectId, ref: "Task", autopopulate: true }
  ],
  tasksCompleted: [
    { type: mongoose.Schema.ObjectId, ref: "Task", autopopulate: true }
  ]
  // TODO: When saving, use something like this: peter.subjects.push(math._id, computer._id)
});
UserSchema.plugin(autopopulate);
module.exports = mongoose.model("User", UserSchema);

task.model.js

const mongoose = require("mongoose");
const autopopulate = require("mongoose-autopopulate");    
const TaskSchema = mongoose.Schema({
  name: String,
  type: String,
  percentage: Number
});
TaskSchema.plugin(autopopulate);    
module.exports = mongoose.model("Task", TaskSchema);

我需要找到 Tasks 的列表,这些 分配给特定的 User。在前端应用程序中,我有 task.service.js 方法:

function getAllUserTasksNotAssignedToUser(userId) {
  $http
    .get("http://localhost:3333/tasks/notAssignedToUser/" + userId)
    .then(function(response) {
      return response.data;
    });
}

在后端,有task.routes.js,这里定义了这条路由:

app.get("/tasks/notAssignedToUser/:userId", tasks.findAllNotAssignedToUser);

...而在task.controller.js中有一个相关的方法:

exports.findAllNotAssignedToUser = (req, res) => {
  console.log("Back controller call");
  User.findById(req.params.userId)
    .then(user => {
      Task.find({ _id: {$nin: user.tasksAssigned }}).then(tasks => {
        res.send(tasks);
      });
    })
    .catch(err => {
      res.status(500).send({
        message:
          err.message ||
          "Some error occurred while retrieving tasks not assigned to the user."
      });
    });
};

如您所见,我的想法是首先找到一个特定的 User,然后是不在该用户的 tasksAssigned 列表中的所有 Tasks。但是,出了点问题,在浏览器的控制台中我得到:

TypeError: Cannot read property 'then' of undefined
    at new AdminUserDetailsController (bundle.js:38254)
    at Object.instantiate (bundle.js:6395)
    at $controller (bundle.js:12447)
    at Object.link (bundle.js:1247)
    at bundle.js:2636
    at invokeLinkFn (bundle.js:11994)
    at nodeLinkFn (bundle.js:11371)
    at compositeLinkFn (bundle.js:10642)
    at publicLinkFn (bundle.js:10507)
    at lazyCompilation (bundle.js:10898) "<div ng-view="" class="ng-scope">"

实施这个的正确方法是什么?

我创建了你的模式并填充了一些假数据:

  let task1 = new Task({
    name: 'task1',
    type: 'type1',
    percentage: '10'
  });
  task1.save();
  let task2 = new Task({
    name: 'task2',
    type: 'type2',
    percentage: '20'
  });
  task2.save();
  let task3 = new Task({
    name: 'task3',
    type: 'type3',
    percentage: '30'
  });
  task3.save();

我在字段 tasksAssigned:

中为此用户添加了两个任务(task1 和 task3)
let user1 = new User({
    username: 'name teste',
      password: '123456',
    firstName: 'first name test',
    lastName: 'last name test',
    friends: [],
    tasksAssigned: ['5b579e94454cb206f6ca338f','5b579e94454cb206f6ca3391'],
    tasksCompleted: []});
  user1.save();

并执行了你的代码。之后我只发现一个问题,当你调用 Task.find 时你需要检查是否找到 用户 ,如果你不检查你将在 user.tasksAssigned行。

User.findById('5b579ee41ac34e0763324fe3')
    .then(user => {
      if(user) {
        Task.find({_id: {$nin: user.tasksAssigned}}).then(tasks => {
          console.log(tasks);
          res.send(tasks);
        });
      }
    })
    .catch(err => {
      console.log('error');
      console.log(err);
      res.status(500).send({
        message:
        err.message ||
        "Some error occurred while retrieving tasks not assigned to the user."
      });
    });

这是 Task then 方法中的控制台日志:

这里是路由在浏览器中的结果:

在此 link 中,您可以查看关于承诺的 Mongoose 文档:Mongoose Promises