[英]Creating documents that contain subdocuments with Mongoose
I am trying to create my MongoDB Atlas database but the subdocument values are not coming through.我正在尝试创建我的 MongoDB Atlas 数据库,但子文档值没有通过。 Am i supposed to loop through them somehow ?我应该以某种方式遍历它们吗? Can't find any solutions.找不到任何解决方案。 Thanks谢谢
Postman request:邮递员要求:
{
"name" : "New Avengers",
"items": [
{"itemName": "Iron Man"},
{"itemName": "Thor"}
],
"tasks": [
{"taskName": "Call Avengers"},
{"taskName": "Watch out for Loki"}
]
}
Database Record :数据库记录:
Model-> project.model.js模型-> project.model.js
const { Schema, default: mongoose, mongo } = require('mongoose');
const itemsSchema = new Schema({
itemName: String,
mainItem: { type: Boolean, default: false }
})
const tasksSchema = new Schema({
taskName: String,
columnLabel1: String,
columnLabel2: String,
})
const projectSchema = new Schema({
name: {
type: String,
required: [true, 'Title is required!'],
unique: true
},
items: [itemsSchema],
tasks: [tasksSchema]
},{
timestamps: true
});
const Project = mongoose.model("Project", projectSchema);
module.exports = Project;
Route -> project.js路线-> project.js
const router = require('express').Router();
let Project = require('../models/project.model');
// Create new Project
router.route('/add').post( async (req, res) => {
const newProject = new Project({
name: req.body.name,
items: [{itemName: req.body.itemName}],
tasks: [{taskName: req.body.taskName}]
});
try {
await newProject.save();
} catch(err) {
res.status(400).json(err);
}
});
module.exports = router;
From the request object, there are no taskName
and itemName
fields.在请求对象中,没有taskName
和itemName
字段。 The newProject
variable should be: newProject
变量应该是:
const newProject = new Project({
name: req.body.name,
items: req.body.items,
tasks: req.body.tasks
});
which items
and tasks
are the arrays received from the req.body
.哪些items
和tasks
是从req.body
接收的数组。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.