我如何获得猫鼬将URL数组推到数组子文档 [英] How can I get mongoose to push an array of urls to an array subdocument

查看:64
本文介绍了我如何获得猫鼬将URL数组推到数组子文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am making a blog system with multiple uploaded images, and multiple posts. I have created an upload screen which allows me to select a few of the previously images, and then posts that to the back end. This all works properly (thanks to some assistance I received at stack overflow), and the console gets this logged from the server:

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

These are image urls from images uploaded to Cloudinary and saved in a mongoDB document. Now I try to save this output to the selected post document with 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.然后,我尝试将字符串数组的字符串推入文档中. 我可以看到它可能最终只能以一个字符串形式出现在文档中,而且我不确定如何正确处理它.我需要以某种方式分隔保存的网址.

I prepend what post ID I wish to add the images to the postImages array, then I separate it into my postID const and log the array of strings. It is the ID I chose. Then I try to push the string of an array of strings into the document. I can see that should probably only end up as one string in the document and I'm not sure how to handle this properly. I need to separate the saved urls somehow.

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

Here is my post DB in Robo 3T:

在Robo 3T上发布数据库

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

What I want is to end up with the highlighted object being one of the urls from the array, and all the other similar objects being one single url leading to an image.

我尝试使用不同的更新功能(updateOne,findByIdAndUpdate,findOneAndUpdate等),并将不同的选项传递给它们.似乎我也尝试过此行中的所有可想像的组合:
{ $push: { imageUrls: { $each: [{ postImages }] } } }

I have tried using different update functions (updateOne, findByIdAndUpdate, findOneAndUpdate, etc.) with different options passed to them as well. It also seems that I have tried every concievable combination in this line:
{ $push: { imageUrls: { $each: [{ postImages }] } } }

全部无效.这是我的模式和模型:

All to no avail yet. Here are my Schemas and models:

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

我不确定我缺少什么. 非常感谢所有帮助和建议,以使它正常工作.

I am not sure what I'm missing. All help and suggestions for getting this to work are greatly appreciated.

推荐答案

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

With trial, error, and trawling through mongoose documentation I eventually found the answer I was looking for. I hope the answer helps you out if you have the same problem.

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

First, I needed to change how I defined my schema because it wasn't meant to be an array of objects, but just an array:

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

出于我的目的,以前的url和id字段不是必需的,因此我也将其删除. 然后,我对猫鼬文档进行了足够的研究,以至偶然发现 $addToSet 并了解它的作用.这似乎是答案,事实证明是这样.要将图片网址保存到文档中,我得到了以下代码:

The former url and id field were unnecessary for my purposes so I removed them as well. Then I looked in the mongoose documentation enough that I stumbled across $addToSetand read about what it does. This seemed like the answer, and it turns out it is. To save my image urls to the document I ended up with this code:

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下的单独字符串.子文档.

Now my code saved my array of urls properly, with each being a separate String under the imageUrls Subdocument.

这篇关于我如何获得猫鼬将URL数组推到数组子文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆