首页 \ 问答 \ MongoDB mongoose子文档创建了两次(MongoDB mongoose subdocuments created twice)

MongoDB mongoose子文档创建了两次(MongoDB mongoose subdocuments created twice)

我使用的是一个简单的表单,可用于将文章注册到网站。

后端看起来像这样:

// Post new article
app.post("/articles", function(req, res){
   var newArticle = {};
   newArticle.title         = req.body.title;
   newArticle.description   = req.body.description;
   var date                 = req.body.date;
   var split                = date.split("/");
   newArticle.date          = split[1]+'/'+split[0]+'/'+split[2];
   newArticle.link          = req.body.link;
   newArticle.body          = req.body.body;
   var platforms = req.body.platforms;
   console.log(platforms);
  Article.create(newArticle, function(err, createdArticle){
      if(err){
          console.log(err.message);
      } else {
           var counter=0;
            platforms.forEach(function(platform){

               var platformed=mongoose.mongo.ObjectID(platform);
               Platform.findById(platformed, function(err, foundPlatform){
                  if(err){
                      console.log(err);
                  } else {
                      counter++;
                        foundPlatform.articles.push(createdArticle);
                        foundPlatform.save();
                        createdArticle.platforms.push(foundPlatform);
                        createdArticle.save();
                        if(counter==platforms.length){
                            res.redirect('articles/' + createdArticle._id);
                        }
                    }
                });
            });

      }


  });

});

platforms字段作为字符串数组传递给后端,一个字符串是一个objectID。 当平台只包含1个字符串,即1个要链接的平台时,一切正常。 当平台包含多个字符串时。 创建的文章具有每个平台的副本。 或者有时只是某些平台的重复

有任何想法吗?

更新1:文章架构:var mongoose = require(“mongoose”);

var articleSchema = new mongoose.Schema({
    title        :   String,
    description  :   String, 
    link         :   String,
    date         :   String,
    body         :   String,
    platforms    :   [
      {
         type: mongoose.Schema.Types.ObjectId,
         ref: "Platform"
      }
   ] 
})

module.exports = mongoose.model("Article", articleSchema);

平台架构:

var mongoose = require("mongoose");

var platformSchema = new mongoose.Schema({
    name        :   String,
    category            :   String,
    contacts          :   [
      {
         type: mongoose.Schema.Types.ObjectId,
         ref: "Contact"
      }
   ],
   website              :   String,
   country              :   String,
   contactInformation   :   String,
   businessModelNotes   :   String,
   source               :   String,
   generalNotes         :   String,
   projects             :   [
      {
         type: mongoose.Schema.Types.ObjectId,
         ref: "Project"
      }
   ],
   articles             :   [
      {
         type: mongoose.Schema.Types.ObjectId,
         ref: "Article"
      }
   ],
   privacy              :   String,
   comments             :   [
      {
         type: mongoose.Schema.Types.ObjectId,
         ref: "Comment"
      }
   ]


});



module.exports = mongoose.model("Platform", platformSchema);

I am using a simple form that can be used to register an article to a website.

the back-end looks like this:

// Post new article
app.post("/articles", function(req, res){
   var newArticle = {};
   newArticle.title         = req.body.title;
   newArticle.description   = req.body.description;
   var date                 = req.body.date;
   var split                = date.split("/");
   newArticle.date          = split[1]+'/'+split[0]+'/'+split[2];
   newArticle.link          = req.body.link;
   newArticle.body          = req.body.body;
   var platforms = req.body.platforms;
   console.log(platforms);
  Article.create(newArticle, function(err, createdArticle){
      if(err){
          console.log(err.message);
      } else {
           var counter=0;
            platforms.forEach(function(platform){

               var platformed=mongoose.mongo.ObjectID(platform);
               Platform.findById(platformed, function(err, foundPlatform){
                  if(err){
                      console.log(err);
                  } else {
                      counter++;
                        foundPlatform.articles.push(createdArticle);
                        foundPlatform.save();
                        createdArticle.platforms.push(foundPlatform);
                        createdArticle.save();
                        if(counter==platforms.length){
                            res.redirect('articles/' + createdArticle._id);
                        }
                    }
                });
            });

      }


  });

});

The platforms field is passed to the back-end as an array of strings, one string being one objectID. When platforms only contains 1 string i.e. 1 platform to be linked to, everything works fine. When platforms contains multiple string. the created article has duplicates of each platform. Or sometimes only duplicates of some platforms

Any ideas?

UPDATE 1: Article Schema: var mongoose = require("mongoose");

var articleSchema = new mongoose.Schema({
    title        :   String,
    description  :   String, 
    link         :   String,
    date         :   String,
    body         :   String,
    platforms    :   [
      {
         type: mongoose.Schema.Types.ObjectId,
         ref: "Platform"
      }
   ] 
})

module.exports = mongoose.model("Article", articleSchema);

Platform Schema:

var mongoose = require("mongoose");

var platformSchema = new mongoose.Schema({
    name        :   String,
    category            :   String,
    contacts          :   [
      {
         type: mongoose.Schema.Types.ObjectId,
         ref: "Contact"
      }
   ],
   website              :   String,
   country              :   String,
   contactInformation   :   String,
   businessModelNotes   :   String,
   source               :   String,
   generalNotes         :   String,
   projects             :   [
      {
         type: mongoose.Schema.Types.ObjectId,
         ref: "Project"
      }
   ],
   articles             :   [
      {
         type: mongoose.Schema.Types.ObjectId,
         ref: "Article"
      }
   ],
   privacy              :   String,
   comments             :   [
      {
         type: mongoose.Schema.Types.ObjectId,
         ref: "Comment"
      }
   ]


});



module.exports = mongoose.model("Platform", platformSchema);

原文:
更新时间:2021-11-08 14:11

最满意答案

您提供的链接是wordpress主题,我尽力复制该样式并反映在bootstrap代码中。 最后,我通过使用cssjQuery的组合成功了。 下面是我的相同风格的代码。

请注意,我已经使用了2个css文件,为了完美地运行轮播,你还需要包含这些文件,在上面给出的行中链接相同!DOCTYPE Html。 休息所有文件都是CDN所以你不必担心它们。

Jquery Snippet

$(".home-solutions-nav-left").click(function() {
  $(".home-solution-items").animate({
      left: "-=250px"
    },
    10, function() {
      /* stuff to do after animation is complete */
      var length = parseInt($(".home-solution-items").css('left'));
      if (length < -1250) {
        resetLeft();
      };
    });
});

function resetLeft() {
  $(".home-solution-items").css('left', '0px');
}

$(".home-solutions-nav-right").click(function() {
  $(".home-solution-items").animate({
      left: "+=250px"
    },
    10, function() {
      /* stuff to do after animation is complete */
      var length1 = parseInt($(".home-solution-items").css('left'));
      if (length1 >= 0) {
        resetRight();
      };
    });
});

function resetRight() {
  $(".home-solution-items").css('left', '-1500px');
}
.home-solution-items {
  left: 0px;
}
<link href="https://www.crowdcontent.com/wp-content/themes/crowdcontent/css/services-nav.css" rel="stylesheet" />
<link href="https://www.crowdcontent.com/wp-content/themes/crowdcontent/css/home-solutions.css" rel="stylesheet" />
<!DOCTYPE HTML>
<html>

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta name="description" content="">
  <meta name="author" content="">
  <title>TechGenium</title>

  <!-- Font-Awesome CDN -->
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css">

  <!-- Latest compiled and minified CSS -->
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" integrity="sha512-dTfge/zgoMYpP7QbHy4gWMEGsbsdZeCXz7irItjcC3sPUFtf0kuFbDz/ixG7ArTxmDjLXDmezHubeNikyKGVyQ==" crossorigin="anonymous">

  <link rel="stylesheet" href="css/services-nav.css">
  <link rel="stylesheet" href="css/home-solutions.css">


</head>

<body>

  <section class="home-solutions" id="home-products">
    <div class="home-solutions-nav-left"></div>
    <div class="container home-solutions-container">
      <div class="home-solution-items" style="width:2500px;left:0px;">
        <ul id="menu-services-nav-with-icons" class="menu">

          <div id="menu-item-405" class="home-solution-item cct-service-nav-item blog-posts menu-item menu-item-type-post_type menu-item-object-page">
            <a href="http://www.techgenium.in/blogs">
              <strong>
                                    <i class="_mi _before fa fa-wordpress"></i>
                                    <span>Blog Posts</span>
                                </strong>
            </a>
          </div>

          <div id="menu-item-406" class="home-solution-item cct-service-nav-item product-description menu-item menu-item-type-post_type menu-item-object-page">
            <a href="http://www.techgenium.in/blogs">
              <strong>
                                    <i class="_mi _before fa fa-shopping-cart"></i>
                                    <span>Product Description</span>
                                </strong>
            </a>
          </div>

          <div id="menu-item-464" class="home-solution-item cct-service-nav-item tweets menu-item menu-item-type-post_type menu-item-object-page">
            <a href="http://www.techgenium.in/blogs">
              <strong>
                                    <i class="_mi _before fa fa-twitter"></i>
                                    <span>Tweets</span>
                                </strong>
            </a>
          </div>

          <div id="menu-item-463" class="home-solution-item cct-service-nav-item facebook-posts menu-item menu-item-type-post_type menu-item-object-page">
            <a href="http://www.techgenium.in/blogs">
              <strong>
                                    <i class="_mi _before fa fa-facebook-square"></i>
                                    <span>Facebook Posts</span>
                                </strong>
            </a>
          </div>

          <div id="menu-item-451" class="home-solution-item cct-service-nav-item metadata menu-item menu-item-type-post_type menu-item-object-page">
            <a href="http://www.techgenium.in/blogs">
              <strong>
                                    <i class="_mi _before fa fa-search"></i>
                                    <span>Metadata</span>
                                </strong>
            </a>
          </div>

          <div id="menu-item-407" class="home-solution-item cct-service-nav-item website-content menu-item menu-item-type-post_type menu-item-object-page">
            <a href="http://www.techgenium.in/blogs">
              <strong>
                                    <i class="_mi _before fa fa-sitemap"></i>
                                    <span>Website Content</span>
                                </strong>
            </a>
          </div>

          <div id="menu-item-408" class="home-solution-item cct-service-nav-item ebooks menu-item menu-item-type-post_type menu-item-object-page">
            <a href="http://www.techgenium.in/blogs">
              <strong>
                                    <i class="_mi _before fa fa-tablet"></i>
                                    <span>eBooks</span>
                                </strong>
            </a>
          </div>

          <div id="menu-item-402" class="home-solution-item cct-service-nav-item white-papers menu-item menu-item-type-post_type menu-item-object-page">
            <a href="http://www.techgenium.in/blogs">
              <strong>
                                    <i class="_mi _before fa fa-file-o"></i>
                                    <span>White Papers</span>
                                </strong>
            </a>
          </div>

          <div id="menu-item-401" class="home-solution-item cct-service-nav-item press-release menu-item menu-item-type-post_type menu-item-object-page">
            <a href="http://www.techgenium.in/blogs">
              <strong>
                                    <i class="_mi _before fa fa-bullhorn"></i>
                                    <span>Press Releases</span>
                                </strong>
            </a>
          </div>

          <div id="menu-item-403" class="home-solution-item cct-service-nav-item newsletters menu-item menu-item-type-post_type menu-item-object-page">
            <a href="http://www.techgenium.in/blogs">
              <strong>
                                    <i class="_mi _before fa fa-newspaper-o"></i>
                                    <span>Newsletters</span>
                                </strong>
            </a>
          </div>

        </ul>
      </div>
    </div>
    <div class="home-solutions-nav-right"></div>
  </section>

  <!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>

  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js" integrity="sha512-K1qjQ+NcF2TYO/eI3M6v8EiNYZfA95pQumfvcVrTHtwQVDG+aHRqLi/ETn2uB+1JqwYqVG3LIvdm9lj6imS/pQ==" crossorigin="anonymous"></script>

</body>

</html>


The link you provided was of wordpress theme, i did my best to copy that style and reflect in bootstrap code. Finally i successed by using the combination of css and jQuery. Below is my code for the same style.

Note that i have used 2 css files which u will also need to include in order to run the carousel perfectly, the link for the same in given above line !DOCTYPE Html. Rest all files are CDN so u need not worry about them.

Jquery Snippet

$(".home-solutions-nav-left").click(function() {
  $(".home-solution-items").animate({
      left: "-=250px"
    },
    10, function() {
      /* stuff to do after animation is complete */
      var length = parseInt($(".home-solution-items").css('left'));
      if (length < -1250) {
        resetLeft();
      };
    });
});

function resetLeft() {
  $(".home-solution-items").css('left', '0px');
}

$(".home-solutions-nav-right").click(function() {
  $(".home-solution-items").animate({
      left: "+=250px"
    },
    10, function() {
      /* stuff to do after animation is complete */
      var length1 = parseInt($(".home-solution-items").css('left'));
      if (length1 >= 0) {
        resetRight();
      };
    });
});

function resetRight() {
  $(".home-solution-items").css('left', '-1500px');
}
.home-solution-items {
  left: 0px;
}
<link href="https://www.crowdcontent.com/wp-content/themes/crowdcontent/css/services-nav.css" rel="stylesheet" />
<link href="https://www.crowdcontent.com/wp-content/themes/crowdcontent/css/home-solutions.css" rel="stylesheet" />
<!DOCTYPE HTML>
<html>

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta name="description" content="">
  <meta name="author" content="">
  <title>TechGenium</title>

  <!-- Font-Awesome CDN -->
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css">

  <!-- Latest compiled and minified CSS -->
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" integrity="sha512-dTfge/zgoMYpP7QbHy4gWMEGsbsdZeCXz7irItjcC3sPUFtf0kuFbDz/ixG7ArTxmDjLXDmezHubeNikyKGVyQ==" crossorigin="anonymous">

  <link rel="stylesheet" href="css/services-nav.css">
  <link rel="stylesheet" href="css/home-solutions.css">


</head>

<body>

  <section class="home-solutions" id="home-products">
    <div class="home-solutions-nav-left"></div>
    <div class="container home-solutions-container">
      <div class="home-solution-items" style="width:2500px;left:0px;">
        <ul id="menu-services-nav-with-icons" class="menu">

          <div id="menu-item-405" class="home-solution-item cct-service-nav-item blog-posts menu-item menu-item-type-post_type menu-item-object-page">
            <a href="http://www.techgenium.in/blogs">
              <strong>
                                    <i class="_mi _before fa fa-wordpress"></i>
                                    <span>Blog Posts</span>
                                </strong>
            </a>
          </div>

          <div id="menu-item-406" class="home-solution-item cct-service-nav-item product-description menu-item menu-item-type-post_type menu-item-object-page">
            <a href="http://www.techgenium.in/blogs">
              <strong>
                                    <i class="_mi _before fa fa-shopping-cart"></i>
                                    <span>Product Description</span>
                                </strong>
            </a>
          </div>

          <div id="menu-item-464" class="home-solution-item cct-service-nav-item tweets menu-item menu-item-type-post_type menu-item-object-page">
            <a href="http://www.techgenium.in/blogs">
              <strong>
                                    <i class="_mi _before fa fa-twitter"></i>
                                    <span>Tweets</span>
                                </strong>
            </a>
          </div>

          <div id="menu-item-463" class="home-solution-item cct-service-nav-item facebook-posts menu-item menu-item-type-post_type menu-item-object-page">
            <a href="http://www.techgenium.in/blogs">
              <strong>
                                    <i class="_mi _before fa fa-facebook-square"></i>
                                    <span>Facebook Posts</span>
                                </strong>
            </a>
          </div>

          <div id="menu-item-451" class="home-solution-item cct-service-nav-item metadata menu-item menu-item-type-post_type menu-item-object-page">
            <a href="http://www.techgenium.in/blogs">
              <strong>
                                    <i class="_mi _before fa fa-search"></i>
                                    <span>Metadata</span>
                                </strong>
            </a>
          </div>

          <div id="menu-item-407" class="home-solution-item cct-service-nav-item website-content menu-item menu-item-type-post_type menu-item-object-page">
            <a href="http://www.techgenium.in/blogs">
              <strong>
                                    <i class="_mi _before fa fa-sitemap"></i>
                                    <span>Website Content</span>
                                </strong>
            </a>
          </div>

          <div id="menu-item-408" class="home-solution-item cct-service-nav-item ebooks menu-item menu-item-type-post_type menu-item-object-page">
            <a href="http://www.techgenium.in/blogs">
              <strong>
                                    <i class="_mi _before fa fa-tablet"></i>
                                    <span>eBooks</span>
                                </strong>
            </a>
          </div>

          <div id="menu-item-402" class="home-solution-item cct-service-nav-item white-papers menu-item menu-item-type-post_type menu-item-object-page">
            <a href="http://www.techgenium.in/blogs">
              <strong>
                                    <i class="_mi _before fa fa-file-o"></i>
                                    <span>White Papers</span>
                                </strong>
            </a>
          </div>

          <div id="menu-item-401" class="home-solution-item cct-service-nav-item press-release menu-item menu-item-type-post_type menu-item-object-page">
            <a href="http://www.techgenium.in/blogs">
              <strong>
                                    <i class="_mi _before fa fa-bullhorn"></i>
                                    <span>Press Releases</span>
                                </strong>
            </a>
          </div>

          <div id="menu-item-403" class="home-solution-item cct-service-nav-item newsletters menu-item menu-item-type-post_type menu-item-object-page">
            <a href="http://www.techgenium.in/blogs">
              <strong>
                                    <i class="_mi _before fa fa-newspaper-o"></i>
                                    <span>Newsletters</span>
                                </strong>
            </a>
          </div>

        </ul>
      </div>
    </div>
    <div class="home-solutions-nav-right"></div>
  </section>

  <!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>

  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js" integrity="sha512-K1qjQ+NcF2TYO/eI3M6v8EiNYZfA95pQumfvcVrTHtwQVDG+aHRqLi/ETn2uB+1JqwYqVG3LIvdm9lj6imS/pQ==" crossorigin="anonymous"></script>

</body>

</html>

相关问答

更多

相关文章

更多

最新问答

更多
  • 您如何使用git diff文件,并将其应用于同一存储库的副本的本地分支?(How do you take a git diff file, and apply it to a local branch that is a copy of the same repository?)
  • 将长浮点值剪切为2个小数点并复制到字符数组(Cut Long Float Value to 2 decimal points and copy to Character Array)
  • OctoberCMS侧边栏不呈现(OctoberCMS Sidebar not rendering)
  • 页面加载后对象是否有资格进行垃圾回收?(Are objects eligible for garbage collection after the page loads?)
  • codeigniter中的语言不能按预期工作(language in codeigniter doesn' t work as expected)
  • 在计算机拍照在哪里进入
  • 使用cin.get()从c ++中的输入流中丢弃不需要的字符(Using cin.get() to discard unwanted characters from the input stream in c++)
  • No for循环将在for循环中运行。(No for loop will run inside for loop. Testing for primes)
  • 单页应用程序:页面重新加载(Single Page Application: page reload)
  • 在循环中选择具有相似模式的列名称(Selecting Column Name With Similar Pattern in a Loop)
  • System.StackOverflow错误(System.StackOverflow error)
  • KnockoutJS未在嵌套模板上应用beforeRemove和afterAdd(KnockoutJS not applying beforeRemove and afterAdd on nested templates)
  • 散列包括方法和/或嵌套属性(Hash include methods and/or nested attributes)
  • android - 如何避免使用Samsung RFS文件系统延迟/冻结?(android - how to avoid lag/freezes with Samsung RFS filesystem?)
  • TensorFlow:基于索引列表创建新张量(TensorFlow: Create a new tensor based on list of indices)
  • 企业安全培训的各项内容
  • 错误:RPC失败;(error: RPC failed; curl transfer closed with outstanding read data remaining)
  • C#类名中允许哪些字符?(What characters are allowed in C# class name?)
  • NumPy:将int64值存储在np.array中并使用dtype float64并将其转换回整数是否安全?(NumPy: Is it safe to store an int64 value in an np.array with dtype float64 and later convert it back to integer?)
  • 注销后如何隐藏导航portlet?(How to hide navigation portlet after logout?)
  • 将多个行和可变行移动到列(moving multiple and variable rows to columns)
  • 提交表单时忽略基础href,而不使用Javascript(ignore base href when submitting form, without using Javascript)
  • 对setOnInfoWindowClickListener的意图(Intent on setOnInfoWindowClickListener)
  • Angular $资源不会改变方法(Angular $resource doesn't change method)
  • 在Angular 5中不是一个函数(is not a function in Angular 5)
  • 如何配置Composite C1以将.m和桌面作为同一站点提供服务(How to configure Composite C1 to serve .m and desktop as the same site)
  • 不适用:悬停在悬停时:在元素之前[复制](Don't apply :hover when hovering on :before element [duplicate])
  • 常见的python rpc和cli接口(Common python rpc and cli interface)
  • Mysql DB单个字段匹配多个其他字段(Mysql DB single field matching to multiple other fields)
  • 产品页面上的Magento Up出售对齐问题(Magento Up sell alignment issue on the products page)