Dipesh Chaulagain
Dipesh Chaulagain

Reputation: 105

How to save array of objects in mongodb with mongoose?

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?

Upvotes: 2

Views: 2172

Answers (2)

Mayur Vaghasiya
Mayur Vaghasiya

Reputation: 1472

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

Upvotes: 1

Rainer Plumer
Rainer Plumer

Reputation: 3753

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

Upvotes: 0

Related Questions