如何将一个字符串数组添加到一个Mongoose模型数组?

时间:2018-04-04 19:41:06

标签: mongodb mongoose

我正在尝试创建一个网站,用户可以上传多个图片并将这些图片上传到Cloudinary并显示在他们的帖子上。一切都工作正常,除了我无法获取图像的URL保存到mongoDB或正确显示。这是我的代码:

var imageLength;
var newImage = [];
router.post("/", isLoggedIn, upload.array("image"),function(req, res){
    imageLength = req.files.length;
    for(var i = 0; i < imageLength; i++){
        cloudinary.uploader.upload(req.files[i].path, function(result) {
            // add cloudinary url for the image to the campground object under image property
            newImage.push(result.secure_url);
            req.body.campground.image[i].push(newImage[i]);
        });
    }
    // add author to campground
    req.body.campground.author = {
                id: req.user._id,
                username: req.user.username
            };
    Campground.create(req.body.campground, function(err, campground) {
        if (err) {
            return res.redirect('back');
        }
        for(var i = 0; i < imageLength; i++){
        }
        res.redirect('/campgrounds/' + campground.id);
    });
    return imageLength = req.files.length;
});

以下是“露营地”的模型:

var mongoose = require("mongoose");

var campgroundSchema = new mongoose.Schema({
   name: String,
   image: [String],
   image_id: [String],
   description: String,
   author: {
     id: {
        type: mongoose.Schema.Types.ObjectId,
        ref: "User"
     },
     username: String
   },
   comments: [
      {
         type: mongoose.Schema.Types.ObjectId,
         ref: "Comment"
      }
   ]
});

module.exports = mongoose.model("Campground", campgroundSchema);

这是我在他们的帖子上显示他们的图像的地方:

<% for(var i = 0; i < campground.image.length; i++){ %>
    <img class="img-responsive" src="<%= campground.image[i] %>">
<% } %>

这是我收到的错误:

/home/ubuntu/workspace/YelpCamp/v10/routes/campgrounds.js:47
            req.body.campground.image[i].push(newImage[i]);
                                     ^

TypeError: Cannot read property '1' of undefined
    at /home/ubuntu/workspace/YelpCamp/v10/routes/campgrounds.js:47:38
    at IncomingMessage.<anonymous> (/home/ubuntu/workspace/YelpCamp/v10/node_modules/cloudinary/lib/uploader.js:500:51)
    at emitNone (events.js:91:20)
    at IncomingMessage.emit (events.js:185:7)
    at endReadableNT (_stream_readable.js:974:12)
    at _combinedTickCallback (internal/process/next_tick.js:80:11)
    at process._tickCallback (internal/process/next_tick.js:104:9)

1 个答案:

答案 0 :(得分:1)

您正在努力将项目推送到带索引的数组中。删除索引并将项目直接推入图像对象。 更换 req.body.campground.image[i].push(newImage[i]);req.body.campground.image.push(newImage[i]);