更新时间:2022-11-25 11:30:52
我创建了您的架构并填充了一些虚假数据:
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