2

I want to save complex data, ie array of objects to mongoose. I have tried few things but i couldn't save the data.

I defined my schema as above and i want to save array of objects that could have any level of nesting. Schema

const mongoose = require('mongoose);
const PostSchema = new mongoose.Schema({
    post: [{}]
});

let PostModel = mongoose.Model('Post', PostSchema)

The Data: enter image description here

Here is the code I used to save the data

app.post('/saveData, async (req, res) => {
    const response = await Post.create(req.body);
    res.json({
        data: response
    });
});

app.listen(8008, () => {
    console.log('server running);
});

The problem is that i cant retrieve the data. it returns array of objects equal to the number of saved array but with no data in it.

How can it be done?

1
  • 3
    please add code instead of screen Commented Feb 6, 2020 at 18:19

2 Answers 2

1

This code works for me.

  const PostModel =  require('./Post');    //declare your model
  app.post('/saveData', async (req, res) => {
    const objModel = new PostModel();
    objModel.post = req.body;   //assign the data post array.
    const response = await objModel.save();
    res.json({
      data: response
    });
  });
Sign up to request clarification or add additional context in comments.

Comments

0

Your post schema looks weird. You have a collection for Posts and then within a posts schema, you have a posts array. What is the point of that? The post collection already is an "array" for posts.

// Perhaps you are looking for something like this.
const PostSchema = new mongoose.Schema({
    title: String,
    content: String,
    level: Number,
    footer: String,
    author: ObjectId,// who wrote the post
    comments: [{
       user: ObjectId,
       comment: String
    }],
    ... createdAt, updatedAt etc
});

Your data structure doesnt seem to match your schema either. e.g await Post.create({posts: req.body});

1 Comment

The only control i have over the data to be saved is that it is the array of object. I am using WYSIWYG editor(editorjs) to write a post. So having schema defined like that wouldnt work for me. Solution answered worked as intended for me!!

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.