Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

I'm trying to post an array of obejcts into my mongodb using node.js

I’m trying to post an array of objects into my mongodb using my obj dummy data, but it just posts an empty array instead

Here’s my code

Schema

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

const mongoose = require('mongoose');

const Schema = mongoose.Schema;
const LevelSchema = new Schema({
    item: [Object],
});

const Items = mongoose.model('items', LevelSchema);

module.exports = Items;

Post routes

const router = require('express').Router();
let Items = require('../models/items.modal');

router.route('/add').post((req, res) => {
  const obj = [
    {
      "name":"name1"
    },
    {
      "name":"name2"
    },
    {
      "name":"name3"
    }

  ]
  const newItems = new Items({obj});

  newItems.save()
    .then(() => res.json('User added!'))
    .catch(err => res.status(400).json('Error: ' + err));
});

module.exports = router;

But some how it just returns an empty array when I run it

Posted Data

   {
        "_id": "90bacff0cc5c2e3734545f34",
        "item": [],
        "__v": 0
    }

>Solution :

Your schema is like this:

const LevelSchema = new Schema({
    item: [Object],
});

So you have to insert something like:

{
  item: [{}]
}

But you are inserting:

{
  obj: [{}]
}

So using const newItems = new Items({item:obj}); should works.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading