使用 Mongoose 创建包含子文档的文档

Creating documents that contain subdocuments with Mongoose

我正在尝试创建我的 MongoDB Atlas 数据库,但是子文档值没有通过。我应该以某种方式遍历它们吗?找不到任何解决方案。谢谢

邮递员请求:

{
    "name" : "New Avengers",
    "items": [
        {"itemName": "Iron Man"},
        {"itemName": "Thor"}
    ],
    "tasks": [
        {"taskName": "Call Avengers"},
        {"taskName": "Watch out for Loki"}
    ]
}

数据库记录:

database record img

模型-> 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; 

路线 -> 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;

从请求对象中,没有 taskNameitemName 字段。 newProject 变量应该是:

const newProject = new Project({
    name: req.body.name,
    items: req.body.items,
    tasks: req.body.tasks
});

其中itemstasks是从req.body接收到的数组。