簡體   English   中英

如何讓 mongoose 將 url 數組推送到數組子文檔

[英]How can I get mongoose to push an array of urls to an array subdocument

我正在制作一個包含多個上傳圖片和多個帖子的博客系統。 我創建了一個上傳屏幕,它允許我 select 一些以前的圖像,然后將其發布到后端。 這一切都正常工作(感謝我在堆棧溢出時收到的一些幫助),並且控制台從服務器獲取此記錄:

[ 'http://res.cloudinary.com/jacobsiler-com/image/upload/v1574344215/SilerGuitars/f8q5d4kedss1tpmhxmwg.jpg',
  'http://res.cloudinary.com/jacobsiler-com/image/upload/v1574344227/SilerGuitars/fveajqk0ehwy5mxywysa.jpg',
  'http://res.cloudinary.com/jacobsiler-com/image/upload/v1574344201/SilerGuitars/lfxwkq8xhhkyxn85oyna.jpg' ]

這些是上傳到 Cloudinary 並保存在 mongoDB 文檔中的圖像的圖像 URL。 現在我嘗試使用 findOneAndUpdate 將此 output 保存到選定的帖子文檔中:

app.post("/post-images", (req, res) => {
  //const post=req
  var postImages = req.body;
  const postID = postImages.shift();
  console.log(postImages);
  Post.findByIdAndUpdate(
    { _id: postID },
    { $push: { imageUrls: { $each: [{ postImages }] } } },
    { lean: true, new: true },
    function(err, foundPost) {
      if (!err) {
        console.log(foundPost);
        res.redirect("/");
      } else {
        console.log("error: " + err);
      }
    }
  );
  //res.redirect("/");
});

我添加了我希望將圖像添加到 postImages 數組的帖子 ID,然后將其分隔到我的 postID const 中並記錄字符串數組。 這是我選擇的ID。 然后我嘗試將字符串數組的字符串推送到文檔中。 我可以看到它可能只以文檔中的一個字符串結尾,我不確定如何正確處理。 我需要以某種方式分隔保存的網址。

這是我在 Robo 3T 中的帖子數據庫:

在 Robo 3T 上發布數據庫

我想要的結果是突出顯示的 object 是數組中的一個 url,所有其他類似的對象都是一個 url 導致圖像。

我嘗試過使用不同的更新函數(updateOne、findByIdAndUpdate、findOneAndUpdate 等),並將不同的選項傳遞給它們。 似乎我已經嘗試了這一行中所有可能的組合:
{ $push: { imageUrls: { $each: [{ postImages }] } } }

一切還無濟於事。 這是我的模式和模型:

//Defining the Image Schema
const imageSchema = {
  url: String,
  id: String
};

const Image = new mongoose.model("Image", imageSchema);

//Defining the Post Schema
const postSchema = {
  title: String,
  content: String,
  imageUrls: [{ url: String }]
};

const Post = new mongoose.model("Post", postSchema);

我不確定我錯過了什么。 非常感謝所有幫助和建議使其正常工作。

通過 mongoose 文檔的反復試驗、錯誤和拖網,我最終找到了我正在尋找的答案。 如果你有同樣的問題,我希望答案能幫助你。

首先,我需要改變我定義架構的方式,因為它並不是一個對象數組,而只是一個數組:

//Defining the Post Schema
const postSchema = {
  title: String,
  content: String,
  imageUrls: [ String ]
};

以前的 url 和 id 字段對我來說是不必要的,所以我也刪除了它們。 然后我查看了足夠多的 mongoose 文檔,以至於我偶然發現了$addToSet並閱讀了它的作用。 這似乎是答案,事實證明確實如此。 要將我的圖片網址保存到文檔中,我最終得到了以下代碼:

app.post("/post-images", (req, res) => {
  //const post=req
  var postImages = req.body;
  const postID = postImages.shift();
  console.log(postImages);
  Post.updateOne(
    { _id: postID },
    {
      $addToSet: { imageUrls: { $each: postImages } }
    },
    function(err, foundPost) {
      if (!err) {
        console.log(foundPost);
        res.redirect("/");
      } else {
        console.log("error: " + err);
      }
    }
  );

現在我的代碼正確保存了我的 url 數組,每個都是imageUrls Subdocument下的一個單獨的字符串。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM