如何迭代对象数组,以便在Mongodb嵌套数组中推送数据

How to iterate through array of object in order to push data in Mongodb nested array

本文关键字:数组 Mongodb 嵌套 数据 何迭代 迭代 对象      更新时间:2023-09-26

我正在开发一个博客应用程序,我正在编写一个在线编辑器,没什么特别的。

在我开始解释我的问题之前,考虑一下我正在使用的模式:

 var blogSchema = restful.model('blog-schema', mongoose.Schema({
   title: String,
   preview: String,
   content: [{tag: String, body: String}],
   comments: [{ body: String, date: Date}],
   createdAt: {type: Date, default: Date.now}
 }

在我的客户端,我使用react来POST数据,看起来像这样:

 [{"type":"h2","body":"azeaeazeae"},{"type":"p","body":"azeaeazeae"}]

然后在express()中我这样做:

 blogSchema.update(
  {title: "please work AGAIN"},
  {
     $pushAll: {
      content: test
     }
 },
 function(err, stat, docs) {
  console.log(stat);
 }
)

然后用POSTMAN检查数据是否保存良好,我得到了这个:

"content": [    
{
  "tag": "[object Object],[object Object]",
  "_id": "57b2eced869e03821d446c38"
}

我的问题,我如何在我的服务器中迭代这个对象数组,然后将每个单独的项目推到各自的位置:tagbody

我确实找到了:

下面是代码:
app.post('/admin', function(req, res) {
   var test = req.body;
   test.map(function(test, i) {
   blogSchema.update(
   {title: "please work AGAIN"},
    {
      $push: {
        content: {
          test: test.type,
          body: test.body
        }
      }
    },
    function(err,stat,dude){
      console.log(stat);
    })
})  

我简单地映射了请求。然后在mongo中执行$push…我很抱歉发布了这个问题。