Search code examples
node.jsarraysmongodbexpressmongoose

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

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.