如何使猫鼬将网址数组推送到数组子文档

时间:2019-11-21 15:21:55

标签: arrays node.js mongoose mongoose-schema

我正在制作一个博客系统,其中包含多个上传的图片和多个帖子。 我创建了一个上传屏幕,使我可以选择一些以前的图像,然后将其发布到后端。 一切都正常工作(由于在堆栈溢出时得到了一些帮助),并且控制台从服务器记录了此信息:

[ '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将输出保存到所选的发布文档中:

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中的帖子数据库:

Post DB on Robo 3T

我想要的最终结果是突出显示的对象是数组中的网址之一,而所有其他类似的对象是指向图像的单个网址。

我尝试使用不同的更新功能(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);

我不确定我缺少什么。 非常感谢所有帮助和建议,以使它生效。

1 个答案:

答案 0 :(得分:0)

通过反复试验,错误和在猫鼬文档中的拖网,最终我找到了所要的答案。如果您遇到相同的问题,希望答案能对您有所帮助。

首先,我需要更改定义架构的方式,因为它并不是要作为对象数组,而只是一个数组:

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

出于我的目的,以前的url和id字段不是必需的,因此我也将其删除了。 然后,我对猫鼬文档进行了足够的研究,以至于偶然发现$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);
      }
    }
  );

现在,我的代码正确保存了我的网址数组,每个网址都是imageUrls Subdocument下的一个单独的字符串。