在节点js中填充

时间:2021-02-14 00:11:28

标签: javascript node.js mongodb mongoose

我是 Node.js 的新手,我正在尝试使用 populate(),但它对我不起作用。

我想用表单填充 user

这是模型

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 getUser = async (req, res) => {
    try {
        const { userId } = req.params;
        if (!userId) return res.status(400).json({ message: "ERROR ID!" });
        const result = await User.findOne({ _id: 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);
    }
};

但这就是我得到的结果

"message": "Success",
"result": {
    **"forms": [],**
    "_id": "5fc917c49aca9b98b8d9b2aa",
    "firstName": "lea",
    "lastName": "bouteflika",
    "email": "inspirez@gmail.com",
    "password": "$2b$10$zJ5Du2YdfJBsz1ah6JYm7uPe1RYMwmmqmq68TxbvbwYnHVcDKNQeq",
    "phone": "+213556865069",
    "__v": 0
}

表格是空的,有人有答案吗?

1 个答案:

答案 0 :(得分:0)

关于populate的代码是正确的,你应该检查id中的forms field是否存在于From模型中,因为当你在集合中插入数据时,只会更新一个集合

const listOfIds = await User.findById(userId );
let result = await Form.find({_id: {$in:[listOfIds.forms]}}).lean()
console.log(result)

因此在Form模型中搜索id列表,如果结果为0则检查插入查询;

并且您可以使用 finById 而不是 finOne

对于插入新表单,这样做

//1
const form = new Form({
  title
 //....
});
//2
let user = await User.findById(userId); // find the user
//3
let newForm = await form.save(); // save new form
//4
user.forms.push(newForm); // push the new form into user for populate
//5
await user.save(); //update user