user6680
user6680

Reputation: 139

array of objects won't POST into mongodb

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
    });
  });
});

Upvotes: 0

Views: 306

Answers (2)

ireshan pathirana
ireshan pathirana

Reputation: 443

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

Upvotes: 1

lawrence-witt
lawrence-witt

Reputation: 9364

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})
});

Upvotes: 0

Related Questions