Search code examples
node.jsmongodbmongoosemongoose-schema

Post Request: Sending values through arrays in Mongoose


I have to send post request of some values from Mongoose. My model file is as below:

const local_lr_urllog_schema = new Schema(
    {       
        domain_name:{
           type: String
        },

        comment:{
            type: String
        },
        local_parameters:[
            {
                source_url: String,
                abstract:String,
                non_abstract: String   
            }
    ],


    }
);

//Export model
module.exports = mongoose.model('Addlogurl', local_lr_urllog_schema);

My controller is as below:

const add_records = async (req, res) => {


     const records = new Addlogurl({

        domain_name:req.body.domain_name,

        comment:req.body.comment,
        local_parameters:[{source_url: req.body.source_url, abstract: req.body.abstract}]
  });




  try {
    await records.save();
  } catch (err) {

    return next(errors);
  } //res.status(messages.status.OK).json(list);
  res.status(messages.status.OK).json({records: records.toObject({ getters: true })});

  };

So my postman throws id values for source_url and abstract.

Postman image

Cant get where I am going wrong?


Solution

  • The problem is right in the construction of new mongoose object only. Here you refer source_url and abstract as req.body.source_url and req.body.abstract, which is wrong because those doesn't come directly under the main level of the object of your request, but only under 1st array element of local_parameters. Changing that should help. The problem here is those values come off as undefined and undefined values are removed by mongoose.

    const records = new Addlogurl({
      domain_name: req.body.domain_name,
    
      comment: req.body.comment,
      local_parameters: [
        { source_url: req.body.local_parameters[0].source_url, abstract: req.body.local_parameters[0].abstract }
      ]
    });