【问题标题】:how to use populate method with react and node.js?如何使用 react 和 node.js 的填充方法?
【发布时间】:2021-05-18 10:45:24
【问题描述】:

我的数据库“用户”和“表单”中有两个集合

每个用户都有一张表格

我使用填充方法来做到这一点,它的工作原理

这是用户的模型:

const Schema = mongoose.Schema


const UserSchema = new Schema({
    firstName: {
        type: 'string',
        required: ' Firstname is Required'
    },
    lastName: {
        type: 'string',
        required: ' lastName is Required'
    },
    email: {
        type: 'string',
        required: ' email is Required'
    },
    phone: {
        type: 'string',

    },
    entrprise: {
        type: 'string'
    },
    password: {
        type: 'string',
        required: ' password is Required'
    },
    forms: [{
        type: mongoose.Schema.Types.ObjectId,
        ref: "Form"
    }

    ]
})

const User = mongoose.model('User', UserSchema)
module.exports = User
这是形式的模型

const Schema = mongoose.Schema

const FormSchema = new Schema({

    logo: {
        type: String,

    },
    compagnyName: {
        type: String,

    },
    title: {
        type: String,


    },
    description: {
        type: String,

    },
    userId: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'User'
    },
    cardQuestion: [
        {
            questionTitle: String,
            questionType: String,
            questionCourte: String,
            questionLongue: String,
            choixMultiple: String,
            caseaCocher: String,
            telechargerFichier: String,
            date: Date,
            heure: String,
            delete: false,
            obligatoire: false,
        }
    ]

})
const Form = mongoose.model('Form', FormSchema)
module.exports = Form

这就是我使用填充方法的方式

const getUser = async (req, res) => {
    try {
        const { userId } = req.params;
        if (!userId) return res.status(400).json({ message: "ERROR ID!" });
        const result = await User
            .findById(userId).populate('forms')

            .exec()

        return res.status(200).json({ message: "Success", result });
    } catch (err) {
        res.status(500).json({ message: "INTERNAL ERROR SERVER!" });
        console.log(err.message);
    }
};

我使用 postman 和 post 方法添加了一个表单用户

当我尝试使用 react 添加表单时

const response = await axios.post(`${API_URL}/form/:userId`,
            {
                ...form,
                userId: localStorage.getItem('userId')
            },
            {
                headers: {
                    authorization: localStorage.getItem('userId')
                }
            }

我得到这样的用户 id 的表单:

 {
        "_id": "6022916bf1d1060f84bc17d0",
        "compagnyName": "axa",
        "description": "recruitement",
        "userId": "60214c5ec0491fcb2d8c29e8",
        "__v": 0,
        "cardQuestion": []
    },

我在表单集合中找到了新表单,但是当我获取用户时,表单字段没有更新(如果我不手动添加表单表仍然为空)

  "result": {
        "forms": [],
        "_id": "60214c5ec0491fcb2d8c29e8",
        "firstName": "moon",
        "lastName": "lea",
        "email": "moon15@gmail.com",
        "password": "$2b$10$bnH0cEBQKktgaKHfBac3L.xUUNEYt9HaqKdLKxLOERrHPG4MVPPFS",
        "phone": "087654266377",
        "__v": 0
    }
}

这就是我添加用户的方式

const register = async (req, res) => {
    try {
        const { firstName, lastName, email, phone, password, forms } = req.body
        if (!firstName || !lastName || !email || !phone || !password)
            return res.status(400).json({ message: 'ERROR!' })


        //CHECKING EXISTING USER
        const found = await User.findOne({ email })
        console.log(found)
        if (found) return res.status(400).json({ message: 'Email already exist' })
        console.log(found)

        //HASHING THE PASSWORD
        const hashPassword = await bcrypt.hash(password, saltRounds)
        console.log(hashPassword)

        //CREATING THE NEW USER
        const newUser = new User()
        newUser.firstName = firstName
        newUser.lastName = lastName
        newUser.email = email
        newUser.password = hashPassword
        if (phone) newUser.phone = phone
        if (forms) newUser.forms = forms
        console.log('i')

        //SAVING THE NEW USER
        const result = await newUser.save()
        console.log(result)
        if (!result) return res.status(400).json({ message: 'failed to create user' })

有人可以帮忙吗?

【问题讨论】:

  • 是肯定的 const Schema = mongoose.Schema const FormSchema = new Schema({ logo: { type: String, }, compagnyName: { type: String, }, title: { type: String, },描述:{类型:字符串,},userId:{类型:mongoose.Schema.Types.ObjectId,参考:'用户'}})const Form = mongoose.model('Form',FormSchema)module.exports = Form跨度>
  • 是的,在问题中
  • 嗨@MounaSis,我认为这里的问题是您正在保存一个表单,其中userId作为参考,但是您正在查询用户,要求填充表单参考(不存在,基于您添加的代码)。您是否尝试过查询表单并填充 userId?
  • 你好,你是对的,谢谢你我纠正了这个,但问题不在这里我的问题是当我在前端添加表单时我在结果中看不到它我得到一个空数组
  • 我在表单模型中引用了用户并使用了填充,它可以工作,非常感谢

标签: node.js reactjs mongoose-populate


【解决方案1】:

也许您必须将 getUser 中的 .populate('forms') 更改为 .populate('form') 我认为它以奇异的形状保存它

【讨论】:

    猜你喜欢
    • 2018-12-13
    • 1970-01-01
    • 2017-05-05
    • 2014-01-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-10
    相关资源
    最近更新 更多