猫鼬-查找不在另一个对象列表中的对象 [英] Mongoose - find objects which are NOT IN another list of objects

查看:88
本文介绍了猫鼬-查找不在另一个对象列表中的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

几天前,我发布了

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:

There are User and Task models. A User contains two lists of Tasks, and those are tasksAssigned and tasksCompleted:

user.model.js

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

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);

我需要找到未分配给特定UserTasks列表.在前端应用程序中,我有 task.service.js 方法:

I need to find a list of Tasks which are not assigned to a particular User. In the frontend application I have task.service.js with a method:

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

在后端,有 task.routes.js ,其中定义了此路由:

On the backend, there is task.routes.js, where this route is defined:

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

...并且 task.controller.js 中有一种相关方法:

...and in task.controller.js there is a relevant method:

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.但是,出了点问题,在浏览器的控制台中,我得到了:

As you can see, my idea was to find a particular User first, and then all the Tasks which are not in that User's tasksAssigned list. However, something went wrong and in browser's console I get:

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">"

实现此目标的正确方法是什么?

What would be the right way to implement this?

推荐答案

我创建了您的架构并填充了一些虚假数据:

I created your schemas and populate with some fake data:

  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):

I added two tasks(task1 and task3) for this user in the field tasksAssigned:

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行中收到错误消息. /p>

And executed your code. After that I found only one problem, when you call Task.find you need to check if the user was found, if you don't check you will receive a error in the user.tasksAssigned line.

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方法内的控制台日志:

This is the console log inside the Task then method:

这是浏览器中路线的结果:

Here the result of the route in the browser:

在此链接中,您可以看到有关承诺的猫鼬文档:猫鼬的承诺

In this link you can see the Mongoose documentation about promises: Mongoose Promises

这篇关于猫鼬-查找不在另一个对象列表中的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆