0

I have an array of objects that is defined in mongoose schema as

  blacklistGroup: {
    userId: { type: String },
    username: { type: String }
  }

I can't figure out why it won't POST into mongodb. I have a console.log that shows that it represents it's schema, but it never appears in mongodb? What am I doing wrong?

console.output

req.body.blacklistGroup
[ { userId: '5e2350c7f88cfb331c4f67de', username: 'artist1' },
  { userId: '5e20c5a139a92512cc7df63c', username: 'artist' } ]
[object Object]

app.js

app.post("/api/listings", checkAuth, (req, res, next) => {
  console.log("req.body.blacklistGroup");
  console.log(req.body.blacklistGroup);
  let blacklistGroup = req.body.blacklistGroup;
  console.log("req.body.blacklistGroup");

  const post = new Post({

    blacklistGroup: req.body.blacklistGroup,

  });

  //saves to database with mongoose
  post.save().then(result => {
    console.log(result);
    res.status(201).json({
      message: "Auction listing created successfully!",
      postId: result._id
    });
  });
});
user6680
  • 79
  • 6
  • 34
  • 78

2 Answers2

1

You can store all user at once. use mongoose insertMany

const Post = require('post');  //mongoose schema

app.post("/api/listings", checkAuth,(req, res, next) => {
  console.log("req.body.blacklistGroup");
  console.log(req.body.blacklistGroup);
  let blacklistGroup = req.body.blacklistGroup;
  console.log("req.body.blacklistGroup");

  const blacklistGroup = req.body.blacklistGroup;

  (async function(){
    await Post.insertMany(blacklistGroup);
    res.status(200).send('Ok');
  })();
});

Or you can use

const Post = require('post');  //mongoose schema

app.post("/api/listings", checkAuth,async (req, res, next) => {
  console.log("req.body.blacklistGroup");
  console.log(req.body.blacklistGroup);
  let blacklistGroup = req.body.blacklistGroup;
  console.log("req.body.blacklistGroup");

  const blacklistGroup = req.body.blacklistGroup;

  await Post.insertMany(blacklistGroup);
  res.status(200).send('Ok');
});

For More Here

0

You don't have an array of objects (or at least you don't want one), you have an object with two properties; userId and username. MongoDB is expecting JSON and it looks like you're trying to send it an array containing that object.

Try this:

let blacklistGroup = req.body.blacklistGroup[0];

To process an array of objects passed as req.body.blacklistGroup, you will have to iterate over it, define a new Post for each object and then send it. I think part of the confusion here is that your Schema is called blacklistGroup but it doesn't refer to a group, it refers to one entry.

const dbCalls = blacklistGroup.map(userObject => {
    const post = new Post({
        blacklistGroup: {
            userId: userObject.userId,
            username: userObject.username
    });

    return new Promise((resolve, reject) => {
        post.save.then(() => {
            resolve();
        })
        .catch(err => {
            reject(err);
        })
    })
});

Promise.all(dbCalls).then(() => {
    res.status(201).json({message: "Auction listings created successfully!"})
})
.catch(err => {
    res.status(500).json({error: err})
});
lawrence-witt
  • 8,094
  • 3
  • 13
  • 32
  • Updated question to reflect multiple users – user6680 Jan 30 '20 at 01:32
  • Not quite sure what you mean about [object Object] vs [object String] but have updated my answer, hope it helps! – lawrence-witt Jan 30 '20 at 01:58
  • I got it converted to [object String] now. I was talking about the datatype of object. – user6680 Jan 30 '20 at 01:59
  • It says ```blacklistGroup.forEach is not a function``` – user6680 Jan 30 '20 at 02:05
  • Oops, I think it should be `blacklistGroup.map` - make sure you're still working with blacklistGroup as an array also. I've also destructured the userObject in my answer which might fix the datatype. – lawrence-witt Jan 30 '20 at 02:10
  • It now says ```blacklistGroup.map is not a function``` Currently it's an ```[object String]``` datatype. Looks like console output above – user6680 Jan 30 '20 at 02:18
  • Refer to ireshan's post - I'm not familiar with MongoDB and did not realise there was an `insertMany` method you could call on arrays. – lawrence-witt Jan 30 '20 at 10:11