如何在 react 和 node.js 中使用 populate 方法?

问题描述

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

每个用户都有一张表格

我使用 populate 方法来做到这一点,它有效

这是用户的模型:

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' })

有人可以帮忙吗?

解决方法

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