【问题标题】:Array in User Schema - mongoose用户模式中的数组 - 猫鼬
【发布时间】:2020-04-22 22:21:13
【问题描述】:

在使用 MERN 堆栈构建应用并为用户的items 完成一个简单的 CRUD API 之后,我想向用户模型添加一个“categories”属性然后他可以将其添加到他的项目中......

为了解释这个应用程序,我计划在将他的数据发布到 MongoDB 时,为每个用户附加一些默认数据,即 categories。不幸的是,我未能将这些类别“发布”到数据库中。

这是我尝试过的不同请求和架构组合

  1. 作为自己的架构

用户路线

const User = require("../models/User")

// @route     POST api/users
// @desc      Regiter a user
// @access    Public
router.post(
  "/",
  [
    check("name", "Please add name")
      .not()
      .isEmpty(),
    check("email", "Please include a valid email").isEmail(),
    check(
      "password",
      "Please enter a password with 6 or more characters"
    ).isLength({ min: 6 })
  ],
  async (req, res) => {
    const errors = validationResult(req)
    if (!errors.isEmpty()) {
      return res.status(400).json({ errors: errors.array() })
    }

    const { name, email, password } = req.body
    console.log(categories)
    try {
      let user = await User.findOne({ email })

      if (user) {
        return res.status(400).json({ msg: "User already exists" })
      }

      user = new User({
        name,
        email,
        password,
      })

      const salt = await bcrypt.genSalt(10)

      user.password = await bcrypt.hash(password, salt)

      await user.save()

      const payload = {
        user: {
          id: user.id
        }
      }

      jwt.sign(
        payload,
        config.get("jwtSecret"),
        {
          expiresIn: 360000
        },
        (err, token) => {
          if (err) throw err
          res.json({ token })
        }
      )
    } catch (err) {
      console.error(err.message)
      res.status(500).send("Server Error")
    }
  }
)

module.exports = router

AuthState 中的请求

    // Register User
      const register = async formData => {
        console.log(formData)
        const expandedFormData = {
          ...formData,
          categories: [
            { name: "Testcategory1", test: 1 },
            { name: "Testcategory2", test: 2 }
          ]
        }
        const config = {
          headers: {
            "Content-Type": "application/json"
          }
        }
        try {
          const res = await axios.post("/api/users", expandedFormData, config)
          console.log(expandedFormData)
          dispatch({
            type: REGISTER_SUCCESS,
            payload: res.data
          })
          loadUser()
        } catch (err) {
          dispatch({
            type: REGISTER_FAIL,
            payload: err.response.data.msg
          })
        }
      }

架构


        const mongoose = require("mongoose")

        const categorieSchema = mongoose.Schema({
          label: String,
          test: Number
        })

        const UserSchema = mongoose.Schema({
          name: {
            type: String,
            required: true
          },
          email: {
            type: String,
            required: true,
            unique: true
          },
          password: {
            type: String,
            required: true
          },
          date: {
            type: Date,
            default: Date.now
          },
          categories: [categorieSchema]
        })

        module.exports = mongoose.model("user", UserSchema)

2。 AuthState 中的请求

....

const expandedFormData = {
      ...formData,
      categories: [{ name: "Testcategory1" }, { name: "Testcategory2" }]
    }

....

架构

....

categories: [
    {
      name: String
    }
  ]

....

3。 AuthState 中的请求

架构

与 2 相同。

....

categories: [
    {
      name: {
        type: String
      }
    }
  ]
....

4。 请求

架构

与 2 相同。

....

  categories: [String]

....

我也阅读了这些主题,但它们没有提供新信息: - Mongoose schema array of objectsSave arrays in Mongoose schema

完整的应用程序可以在https://github.com/mortizw/Repio-2.0查看 除了关于如何使这个模型工作的一些想法之外,我很高兴有一些关于如何迭代测试/接近这种“模式问题”的技巧,就像你可以通过控制台记录一些东西一样。

【问题讨论】:

  • 你能把你的后端怎么样saving users?
  • Schema const categorieSchema = mongoose.Schema({ name: String, test: Number }) && categories: [categorieSchema] 应该可以工作,除了categories 之外的同一请求中的其他字段是否正在更新?

标签: node.js reactjs mongodb express mongoose


【解决方案1】:

当您创建 new User 时,您没有传递 Categories 这就是它没有被保存的原因。

首先,这个 Schema 可以正常工作

categories: [
    {
      name: {
        type: String
      }
    }
  ]

那么您需要将您的user route 更新为此

const { name, email, password,categories } = req.body

user = new User({
        name,
        email,
        password,
        categories
      })

还要确保您只在前端的类别中传递name,因为您的架构只有name

你的前端应该是这样的

const expandedFormData = {
          ...formData,
          categories: [
            { name: "Testcategory1"},
            { name: "Testcategory2"}
          ]
        }

【讨论】:

  • 谢谢,我想我也可以在以下位置添加默认值:user = new User({ name, email, password, categories: [{ name: "Testcategory1" }, { name: "Testcategory2" }] })
  • 是的,那也可以!只要架构正确
猜你喜欢
  • 2023-03-13
  • 2019-10-30
  • 2015-05-15
  • 2012-02-02
  • 2019-08-21
  • 1970-01-01
  • 2023-03-04
  • 2016-08-05
  • 2017-04-22
相关资源
最近更新 更多