使用猫鼬在mongodb中创建数组字段

时间:2019-11-01 10:03:28

标签: node.js mongodb mongoose mongoose-schema

我正在尝试在mongodb中创建一个集合,其中名为lists的字段将包含linklinkName的数组。我可以成功创建两个单独的字段linklinkName,但是无法在lists内存储值。

mongodb的模型代码:-

const socialSchema = new Schema({
    lists: [{
        link:{ formType: String},
        linkName: { formType: String}
    }]
})

API代码:-(此代码仅用于创建,稍后将尝试使用findOneAndUpdate更新现有字段

router.route('/', [auth]).post(async (req, res) => {
    const {linkName, link } = req.body
    try {
        console.log(req.body)//Ex. { linkName: 'facebook', link: 'www.facebook.com'}
        const social = new Social({
          //Stuck here!!!
        })
        await social.save()
        res.json(social)
    } catch (err) {
        console.error(err.message);
        res.status(500).send('Server Errors')
    }
   }
)

部分前端代码(反应)

const [formData, setFormData] = useState({
        linkName: '',
        link: ''
  });
  const {linkName, link} = formData

  const onChange = e =>
  setFormData({ ...formData, [e.target.name]: e.target.value });

  const handleSubmit = async e => {
    e.preventDefault()
    const socialList = {
      linkName,
      link
    }
    try {
      const config = {
                headers: {
                    'Content-Type': 'application/json'
                }
            };
      const body = JSON.stringify(socialList)
      const res = await Axios.post('/api/social', body, config)
      console.log(res)
    } catch (err) {
      console.error(err);
    }
  }

1 个答案:

答案 0 :(得分:0)

在您的架构中,从{formType: String}更改为{type: String}

const data = {link: req.body.link, linkName: req.body.linkName};
Social.create({
  links: [data]
});

这应该有效。


我测试过的我的完整代码

const schema = new mongoose.Schema({
  links: [
    {
      link: { type: String },
      linkName: { type: String }
    }
  ]
});

const Model = mongoose.model("test", schema);

const doc = { link: "link", linkName: "linkname" };

Model.create({
    links: [doc]
});