【问题标题】:How to save array of Strings in Node Mongodb如何在 Node Mongodb 中保存字符串数组
【发布时间】:2021-08-29 11:16:35
【问题描述】:

我有一个字符串数组,我想在 Node/express 中保存在 Mongodb 中,它正在将 Empty 数组保存在 Mongodb 中

const multiImagesSchema = mongoose.Schema({
    names:Array
})

import ImgArray from '../../Model/multiImages.js'

let imgNames = req.files.map(imgName=>{ 
            return imgName.originalname  
        })

      // console,log(imgNames)
       //result in console:   ['Apple,png', 'Grapes.png','Ornage.png','Banana.png'] 

        const imageArray = new ImgArray(imgNames)
        await imageArray.save()

【问题讨论】:

    标签: javascript node.js mongodb express mongoose


    【解决方案1】:

    您必须将具有模式模型中定义的属性的对象传递给创建函数(在您的情况下是具有names 属性的对象)。您正在传递 imgNames 数组。像这样改变你的代码:

    await ImgArray.create({ names: imgNames });
    

    【讨论】:

      【解决方案2】:

      您的模型需要有一个接受如下数组的字段:

      const ImgArraySchema = mongoose.Schema({
      names: [{
      type: String,
      required: true
      }]
      })
      

      然后保存一个数组,这样做:

      const imageArray = new ImgArray({names: imgNames})
      const imgarray = await imageArray.save()
      .catch((err) => (res.status(500).send({err: err.message})))
      if (imgarray) {
      return res.status(200).send({success: true, imgarray})
      }
      return res.status(400).send({success: false, error: ""})
      

      【讨论】:

        猜你喜欢
        • 2014-11-07
        • 1970-01-01
        • 2011-10-18
        • 2019-03-18
        • 2021-07-12
        • 2014-05-29
        • 1970-01-01
        • 2022-06-16
        • 2013-08-13
        相关资源
        最近更新 更多