Home > Mobile >  Creating documents that contain subdocuments with Mongoose
Creating documents that contain subdocuments with Mongoose

Time:05-31

I am trying to create my MongoDB Atlas database but the subdocument values are not coming through. 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 :

database record img

Model-> 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

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;

CodePudding user response:

From the request object, there are no taskName and itemName fields. The newProject variable should be:

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.

  • Related