【问题标题】:How to iterate through array of object in order to push data in Mongodb nested array如何遍历对象数组以便在 Mongodb 嵌套数组中推送数据
【发布时间】:2016-12-22 17:08:54
【问题描述】:

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

在我开始解释我的问题之前,请考虑一下我正在使用的这个架构:

 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 来发布如下所示的数据:

 [{"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

【问题讨论】:

    标签: javascript arrays mongodb express mongoose


    【解决方案1】:

    我确实找到了:

    这里是代码:

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

    我简单地映射了 req.body,然后在 mongo 中执行了 $push ...我很抱歉发布了这个问题。不过很开心!

    【讨论】:

    • 还有一个问题,为什么 mongodb 为每个推送的元素创建一个 _id ? { "test": "h2", "body": "一些正文", "_id": "57b2f1260397195a1f49ac64" }
    • This link 可能会在评论中为您提供问题的答案。
    猜你喜欢
    • 2020-07-25
    • 2014-02-08
    • 2018-09-26
    • 2022-01-14
    • 2021-07-30
    • 2018-08-28
    • 1970-01-01
    • 2021-12-28
    • 2019-03-28
    相关资源
    最近更新 更多