最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

如何获得猫鼬将URL数组推入数组子文档

网站源码admin17浏览0评论

如何获得猫鼬将URL数组推入数组子文档

如何获得猫鼬将URL数组推入数组子文档

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

[ '.jpg',
  '.jpg',
  '.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

我想要的最终结果是,突出显示的对象是数组中的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);

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

回答如下:

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

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

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

前一个url和id字段对于我来说是不必要的,因此我也将其删除。然后,我对猫鼬文档进行了足够的研究,以至于偶然发现$addToSet并了解其功能。这似乎是答案,事实证明确实如此。要将图片网址保存到文档中,我得到了以下代码:

$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下的单独字符串。

发布评论

评论列表(0)

  1. 暂无评论