1

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
    }

1 Answer 1

2

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.

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.