Py学习  »  MongoDB

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

Dipesh Chaulagain • 6 年前 • 1494 次点击  

我如上所述定义了模式,并希望保存可以有任何嵌套级别的对象数组。

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

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

数据: enter image description here

保存数据

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

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

问题是我无法检索数据。它返回的对象数组等于已保存数组的数目,但其中没有数据。

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/56176
文章 [ 2 ]  |  最新文章 6 年前
Rainer Plumer
Reply   •   1 楼
Rainer Plumer    6 年前

你的后模式看起来很奇怪。 这有什么意义? post集合已经是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
});

例如 等待Post.create({posts:req.body});

Mayur Vaghasiya
Reply   •   2 楼
Mayur Vaghasiya    6 年前

这个密码对我有效。

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