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

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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

7 Comments

Updated question to reflect multiple users
Not quite sure what you mean about [object Object] vs [object String] but have updated my answer, hope it helps!
I got it converted to [object String] now. I was talking about the datatype of object.
It says blacklistGroup.forEach is not a function
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.
|

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.