我正在学习猫鼬关系,并陷入了这个问题...有人告诉我我在哪里错了..?并且有更好的方法做到这一点吗?
Employee.js
const mongoose = require("mongoose");
const { departmentSchema, addDepartment } = require("./Departments");
const schema = new mongoose.Schema();
const employeeModel = mongoose.model("Employee", {
Name: { type: String, required: true, minlength: 5, maxlength: 50 },
Department: departmentSchema
});
async function addEmployee(Employee, Department, Language, Framework) {
const result = await new employeeModel({
...Employee,
Department: addDepartment(Department, Language, Framework)
});
return await result.save();
}
Department.js
const mongoose = require("mongoose");
const { languageSchema, addLanguage } = require("./Language");
const departmentSchema = new mongoose.Schema({
Depart: { type: String, required: true, minlength: 5, maxlength: 50 },
Languages: languageSchema
});
const DepartmentModel = mongoose.model("Department", departmentSchema);
async function addDepartment(Department, Language, Framework) {
const result = await new DepartmentModel({
...Department,
Languages: addLanguage(Language, Framework)
});
return await result.save();
}
module.exports = {
departmentSchema,
addDepartment
};
Language.js
const mongoose = require("mongoose");
const { frameworkSchema, addFramework } = require("./Frameworks");
const languageSchema = new mongoose.Schema({
Language: { type: String, required: true },
Framework: [frameworkSchema]
});
const languageModel = mongoose.model("Language", languageSchema);
async function addLanguage(Language, Framework) {
const result = await new languageModel({
...Language,
Framework: addFramework(Framework)
});
return await result.save();
}
module.exports = {
languageSchema: languageSchema,
addLanguage
};
Framework.js
const mongoose = require("mongoose");
const frameworkSchema = new mongoose.Schema({
Name: { type: String, required: true, minlength: 4, maxlength: 50 },
Version: { type: String, required: true, minlength: 1, maxlength: 50 }
});
const frameworkModel = mongoose.model("Framework", frameworkSchema);
async function addFramework(Framework) {
const result = await new frameworkModel(...Framework);
return await result.save();
}
module.exports = {
frameworkSchema,
addFramework
};
来自Framework.js的错误
Found non-callable @@iterator
我想做的是
每个->代表一个新对象(集合)
我知道对于像我这样的新手来说有点复杂... 我是MySql数据库用户,我喜欢它,但现在我正试图掌握NoSql ...
先谢谢您了:)
答案 0 :(得分:0)
我将向您展示一个示例: 假设您已经具有 employSchema 了:
const {Schema} = mongoose;
const employeeModel = mongoose.model("Employee", new Schema({
Name: { type: String, required: true, minlength: 5, maxlength: 50 },
Department: {type: Schema.Types.ObjectId, ref: "Department"}
}));
在上述模型中,我使用 ref 属性通过 ObjectId 连接到部门模型(这意味着“部门”集合中的“ _id”属性)。
例如:您将像这样创建一个新的employeeModel:
let newEmployee = new employeeModel("Employee Name", Department ID here).
您绝对相反或为他人做。 并且您需要使用 .populate()函数来查询数据库。 示例:
employModel.find({}).populate("Department").exec(callback what you want to do);
您可以在以下位置阅读正式文档:https://mongoosejs.com/docs/populate.html
答案 1 :(得分:0)