简体   繁体   中英

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: 在此处输入图片说明

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?

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

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. eg await Post.create({posts: req.body});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM