1

So I'm working on a blog app, and I'm coding an online editor right now, nothing fancy.

Before I start to explain my problem consider this schema which I'm using :

 var blogSchema = restful.model('blog-schema', mongoose.Schema({
   title: String,
   preview: String,
   content: [{tag: String, body: String}],
   comments: [{ body: String, date: Date}],
   createdAt: {type: Date, default: Date.now}
 }

On my client side, I'm using react to POST data which looks like this :

 [{"type":"h2","body":"azeaeazeae"},{"type":"p","body":"azeaeazeae"}]

Then within express() I do this :

 blogSchema.update(
  {title: "please work AGAIN"},
  {
     $pushAll: {
      content: test
     }
 },
 function(err, stat, docs) {
  console.log(stat);
 }
)

Then with POSTMAN I check if the data is well stored and I got this :

"content": [    
{
  "tag": "[object Object],[object Object]",
  "_id": "57b2eced869e03821d446c38"
}

My question, how in my server can I iterate through this array of object and then push every single item to its respective place : tag and body.

1 Answer 1

1

I did find it :

here is the code :

app.post('/admin', function(req, res) {
   var test = req.body;

   test.map(function(test, i) {
   blogSchema.update(
   {title: "please work AGAIN"},
    {
      $push: {
        content: {
          test: test.type,
          body: test.body
        }
      }
    },
    function(err,stat,dude){
      console.log(stat);
    })
})  

I simple mapped the req.body and then perform a $push within mongo... I'm sorry to have posted this question. So happy though !

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

2 Comments

One more question, why mongodb creates an _id for each element pushed ? { "test": "h2", "body": "Some body text", "_id": "57b2f1260397195a1f49ac64" }
This link may give you the answer for the question in the comment.

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.