【发布时间】:2020-03-17 13:57:22
【问题描述】:
我正在制作一个包含多个上传图片和多个帖子的博客系统。 我创建了一个上传屏幕,允许我选择一些以前的图像,然后将其发布到后端。 这一切都正常工作(感谢我在堆栈溢出时收到的一些帮助),并且控制台从服务器获取此记录:
[ '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 中的帖子数据库:
我想要的结果是突出显示的对象是数组中的一个 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);
我不确定我错过了什么。 非常感谢所有帮助和建议使其正常工作。
【问题讨论】:
标签: arrays node.js mongoose mongoose-schema