我使用mongoose 4.11.10,我宣布了2个型号:User&任务。我的用户模型是:
let UserSchema = mongoose.Schema({
name: {
type: String,
required: true,
minlength: 1,
maxlength: 15
}
});
let User = mongoose.model("UserModel", UserSchema);
来自用户模型的片段:
let TaskSchema = mongoose.Schema({
userName: {
type: mongoose.Schema.ObjectId,
ref: "User",
required: false,
minlength: [1, "Invalid name"],
maxlength: [15, "Too big name"]
}
});
let Task = mongoose.model("TaskModel", TaskSchema);
我有表格,我输入所有这些值:
<p>Add new task: </p>
<form action="/api/tasks/" method="post">
Name:
<input type="text" name="name">
<br>
Definition:
<input type="text" name="definition">
<br>
Status:
<input type="text" name="status">
<br>
Responsible user:
<input type="text" name="userName">
<br>
Deadline:
<input type="date" name="deadline" >
<br><br>
<input type="submit" value="SEND">
</form>
在服务器端我有控制器:
api.post("/tasks/", (req, res) => {
let name = req.body.name;
let definition = req.body.definition;
let status = req.body.status;
let userName = req.body.userName;
let deadline = req.body.deadline;
if (userName.length < 1) {
Task.create({name: name}, {definition: definition}, {status: status}, {userName: "not delegated yet"}, {deadline: deadline})
.then(() => {
console.log("Insertion successful");
res.redirect("/api/tasks");
})
.catch(err => {
console.log("Cannot insert");
throw err;
})
} else {
Task.create({name: name}, {definition: definition}, {status: status}, {userName: userName}, {deadline: deadline})
.then(() => Task.findOne({name: name}).populate("userName"))
.then(() => {
console.log("Insertion successful");
res.redirect("/api/tasks");
})
.catch(err => {
console.log("Cannot insert");
throw err;
})
}
});
正如你所看到的,我想链接2个模式:我想在指定用户上“委托”任务,但现在populate()mongoose方法不起作用:(我该如何解决这个问题?
我们将不胜感激任何帮助!
答案 0 :(得分:0)
我发现了类似的问题,这可能对您有所帮助https://stackoverflow.com/questions/14730676/linking-2-mongoose-schemas
答案 1 :(得分:0)
您将userName
的类型定义为ObjectId,但name
的类型是字符串。这是一种不匹配,人口无法发挥作用。
将类型更改为String
。
let TaskSchema = mongoose.Schema({
user: {
type: String,
ref: 'User',
required: false,
minlength: [1, "Invalid name"],
maxlength: [15, "Too big name"]
}
});
我建议您将userName
重命名为user
,以便在查询时添加更多清晰度
Task.findOne(...).populate('user').exec(function (err, task) {
console.log(task.user.name);
});
如果您尝试在不向架构添加tasks
数组的情况下获取特定用户的所有任务,则可以使用virtual population
UserSchema.virtual('tasks', {
ref: 'Task', // The model to use
localField: 'name', // Find task where `localField`
foreignField: 'user' // is equal to `foreignField`
});
然后你可以做
User.findOne(...).populate('tasks').exec(function (err, user) {
console.log(user.tasks);
});