首页 > 解决方案 > 使用nodejs在mongodb的许多相互关联的集合中创建许多文档的最佳方法

问题描述

我正在尝试一次或一次调用在多个集合中创建文档。场景是: 1. 尝试添加用户,但与此同时,我正在尝试添加钱包收藏和购物车收藏。这 2 个集合应包含用户 ID,用户集合应包含钱包和购物车 ID。我做了一些工作,但它太长了,它似乎不是最好的方法。需要比这更好的方法的建议。

exports.signupAUserMain = (req, res, next) => {
    User.find({ email: req.body.email }).exec()
        .then(result => {

            if (result.length !== 0) {
                return res.status(400).json({
                    message: 'User is already present. Try with another email'
                })
            } else {
                bcrypt.hash(req.body.password, 10, (err, hash) => {
                    if (err) {
                        return res.status(500).json({
                            message: 'Unable to encrypt password'
                        });
                    }

                    const user = new User({
                        _id: mongoose.Types.ObjectId(),
                        firstName: req.body.firstName,
                        lastName: req.body.lastName,
                        role: req.body.role,
                        email: req.body.email,
                        password: hash
                    });

                    user.save()
                        .then(response => {

                            logger.customLogger('User created successfully');

                            const payback = new Paybackpoints({
                                _id: mongoose.Types.ObjectId(),
                                userId: response._id
                            })

                            payback.save()
                                .then(responseW => {
                                    logger.customLogger(`User created successully. Also payback wallet is created for the user,\n ${responseW}`);
                                    User.findByIdAndUpdate(response._id, { $set: { paybackId: responseW._id } }).exec()
                                        .then(responseupdation => {
                                            logger.customLogger(`Updated user with payback id`);

                                            const cart = new cart({
                                                _id: mongoose.Types.ObjectId(),
                                                user: response._id
                                            })
                                            cart.save()
                                                .then(responseC => {
                                                    logger.customLogger(`User created successully. Also payback wallet and cart is created for the user,\n ${responseC}`);

                                                    res.status(201).json({
                                                        message: 'User created successully. Also payback wallet is created for the user',
                                                        wallet: responseW._id,
                                                        cart: responseC._id
                                                    })
                                                })
                                                .catch(error => {
                                                    res.status(500).json({
                                                        error
                                                    })
                                                })

                                        })


                                })

                                .catch(error => {
                                    User.findByIdAndRemove(response._id).exec()
                                        .then(result => {
                                            if (result) {
                                                logger.customLogger(`User creation rolled back as wallet creation got interrupted`);
                                                res.status(500).json({
                                                    message: 'User creation rolled back as wallet creation got interrupted',
                                                    error
                                                })
                                            }
                                        })
                                        .catch(newErr => {
                                            logger.customLogger(`Payback Wallet creation was unsuccessful and so user creation was trying to roll back to null but rather got interrupted`);
                                            res.status(500).json({
                                                message: 'Payback Wallet creation was unsuccessful and so user creation was trying to roll back to null but rather got interrupted',
                                                error1: error,
                                                error2: newErr
                                            })
                                        })

                                })
                        })
                        .catch(error => {
                            logger.customLogger(`Failed to create user, ${error}`)
                            res.status(500).json({
                                message: 'Failed to create user',
                                error
                            })

                        });
                })
            }


        })
        .catch(error => {
            logger.customLogger(error);
            res.status(500).json({
                error
            })
        })



}

标签: javascriptnode.jsmongodb

解决方案


解决方案是您需要在保存文档之前创建自定义_id并将其保存为 mongo 。_id

首先创建所有自定义 3 _id 如下

const UserId = new mongoose.Types.ObjectId().toHexString(); 
const paybackId = new mongoose.Types.ObjectId().toHexString();
const cartId = new mongoose.Types.ObjectId().toHexString();

在 Schema 中设置_id属性false,您的所有 3 个 Schema 如下所示

const User = new mongoose.Schema({
    //need to add your remaning fields
    paybackId: String,
    cartId: String
},{ _id: false });

const Payback = new mongoose.Schema({
    userId: String
},{ _id: false });

const Cart = new mongoose.Schema({
    userId: String
},{ _id: false });

现在您可以按照以下方式将所有 3 个与参考文档平行插入

let userObj = new User({
    _id: UserId, //5cd5308e695db945d3cc81a9
    paybackId: paybackId,
    cartId: cartId
});
userObj.save();

let paybackObj = new Payback({
    _id: paybackId,
    userId: UserId
});
paybackObj.save();

let cartObj = new Cart({
    _id: cartId,
    userId: UserId
});
cartObj.save();

推荐阅读