如何将req.body添加到猫鼬数组中?

时间:2020-03-26 19:46:52

标签: arrays mongoose

我觉得我已经做了很多尝试。

我想将我的.ejs文件中的图像添加到图库数组中。 req.body工作正常,我只是无法将这些图像添加到图库数组中。

router.post("/", function(req, res){
    var name            = req.body.name;
    var mainImage       = req.body.mainImage;
    var image           = {'image': req.body.image};  <----------
    var gallery         = galArray(image);   <----------
    var description     = req.body.description;
    var price           = req.body.price;
    var newBike         = {name: name, mainImage: mainImage, gallery: gallery, description: description, price: price}
    Bike.create(newBike, function(err, newlyCreated){
        if(err){
            console.log(err);
        } else {
            console.log(newlyCreated);
            res.redirect("/shop/bikes");
        }
    });
});

const galArray = img => {
    var gal = [];                  <-----------------------
    return gal.push(img);
}
const bikeSchema = new mongoose.Schema({
        // IDENTITY
        name: String,
        mainImage: String,
        gallery: [{

                image: String. <----------
        }    
        ],
        description: String,

我尝试过:

var image   = req.body.image;
var gallery = gallery.push(image);
var image   = {'image': req.body.image};
var gallery = gallery.push(image);

编辑: 这是将函数更改为以下内容后得到的错误消息:

const galArray = img => {
    var gal = [];              
    gal.push(img);
    return gal;
}

这是错误消息:

 stringValue: '"[\n' +
        "  '/public/img/Bikes/Road/superstar bottom bracket.jpeg',\n" +
        "  '/public/img/Bikes/Road/superstar bottom bracket.jpeg',\n" +
        "  '/public/img/Bikes/Road/superstar bottom bracket.jpeg',\n" +
        "  '/public/img/Bikes/Road/superstar bottom bracket.jpeg',\n" +
        "  '',\n" +
        "  '',\n" +
        "  '',\n" +
        "  ''\n" +
        ']"',
      kind: 'String',
      value: [Array],
      path: 'image',
      reason: [MongooseError],
      message: 'Cast to String failed for value "[\n' +
        "  '/public/img/Bikes/Road/superstar bottom bracket.jpeg',\n" +
        "  '/public/img/Bikes/Road/superstar bottom bracket.jpeg',\n" +
        "  '/public/img/Bikes/Road/superstar bottom bracket.jpeg',\n" +
        "  '/public/img/Bikes/Road/superstar bottom bracket.jpeg',\n" +
        "  '',\n" +
        "  '',\n" +
        "  '',\n" +
        "  ''\n" +
        ']" at path "image"',
      name: 'CastError'
    }
  },
  _message: 'Bike validation failed',
  name: 'ValidationError'
}

1 个答案:

答案 0 :(得分:0)

Array#push将元素推入数组后,返回数组的新长度。

const galArray = img => {
    var gal = [];
    gal.push(img); // You should push the element into the array
    return gal; // And then return the array
}