1

I am trying to post a simple request which includes array of objects. I have created a model and passing the data as per the model. I am having trouble accessing body parameters as it contains array of data. I am able to store line item data by req.body.tasks[0] which is not a standrad way of storing details in mongodb. I am looking for a standrad way of storing array of data in mongodb

Controller:


let createBug = (req, res) => {
  console.log(req.body.tasks[0].subtask[0].description)
  for (var key in req.body) {
    if (req.body.hasOwnProperty(key)) {
      item = req.body[key];
      console.log(item);
    }
  }
  const createBug = new listModel({
    title: req.body.title,
    tasks: [{
      title: req.body.tasks[0].title,
      description: req.body.tasks[0].description,
      subtask: [{
        description: req.body.tasks[0].subtask[0].description
      }]
    }]
  }).save((error, data) => {
    if (data) {
      let apiResponse = response.generate(false, null, 201, data);
      res.status(201).send(apiResponse);
    } else {
      let apiResponse = response.generate(true, error, 404, null);
      res.status(404).send(apiResponse);
    }
  });
};

body:

{
"title":"sample title",
"tasks":[{
    "title": "task 1",
    "description":"task1 description",
    "subtask":[{
         "description":"task3 description"
    }]
    }]   
}

Model:

const mongoose = require("mongoose");
const mySchema = mongoose.Schema;
let subtask = new mySchema({
  description: String
})

let taskdata = new mySchema({
  title: String,
  description: String,
  subtask: [subtask]
});

let listSchema = new mySchema({
  title: {
    type: String,
    require: true,
  },

  tasks: [taskdata],

  owner: {
    type: mongoose.Schema.Types.ObjectId,

    ref: "users",
  }
});
module.exports = mongoose.model("list", listSchema);

1 Answer 1

1

I think you're overcomplicating things here a little bit. The request body exactly matches the model definitions, so you can simply pass the req.body object to your mongoose model:

const createBug = new listModel(req.body).save((error, data) => { ... }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.