我怎样才能让 mongoose 将一组 url 推送到一个数组子文档

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

我正在制作一个包含多个上传图片和多个 post 的博客系统。 我创建了一个上传屏幕,允许我 select 之前的一些图像,然后 post 将其发送到后端。 这一切都正常工作(多亏了我在堆栈溢出时收到的一些帮助),并且控制台从服务器记录了这个:

[ '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' ]

这些图像 url 来自上传到 Cloudinary 并保存在 mongoDB 文档中的图像。 现在,我尝试使用 findOneAndUpdate 将此输出保存到 selected post 文档:

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("/");
});

我在 post ID 前面添加了我希望将图像添加到 postImages 数组的内容,然后我将它分成我的 postID 常量并记录字符串数组。这是我选择的ID。然后我尝试将字符串数组的字符串推送到文档中。 我可以看到它可能只会在文档中作为一个字符串结束,我不确定如何正确处理它。我需要以某种方式分离保存的 urls。

这是我在 Robo 3T 中的 post 数据库:

Post DB on Robo 3T

我想要的是最终突出显示的对象是数组中的 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 并了解了它的作用。这似乎是答案,事实证明确实如此。要将我的图像 urls 保存到文档中,我最终使用以下代码:

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.

下的一个单独的字符串