【发布时间】:2018-12-31 09:00:43
【问题描述】:
几天前我发布了this question。因为没找到 工作解决方案,我已经稍微改变了我的应用程序的结构,这就是为什么 我正在发布这个新问题。
有User 和Task 型号。一个User 包含两个Tasks 列表,它们是tasksAssigned 和tasksCompleted:
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">"
实现这一点的正确方法是什么?
【问题讨论】:
标签: mongoose mean-stack