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

时间:2018-07-23 20:26:18

标签: mongoose mean-stack

  

几天前,我发布了this 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);

我需要找到{strong>未未分配给特定Tasks的{​​{1}}列表。在前端应用程序中,我有 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列表中的所有Tasks。但是,出了点问题,在浏览器的控制台中,我得到了:

tasksAssigned

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

1 个答案:

答案 0 :(得分:1)

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

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

Tasks

我在 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();

User with tasks

并执行您的代码。之后,我只发现一个问题,当您调用Task.find时,您需要检查是否找到用户,如果不进行检查,则user.tasksAssigned行中将收到错误消息。 / p>

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

console log

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

Result

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