简体   繁体   English

如何使用 mongoose 在 mongodb 中保存对象数组?

[英]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.您有一个 Posts 集合,然后在一个 posts 架构中,您有一个 posts 数组。 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});例如 await Post.create({posts: req.body});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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