Mongoose:如何将数据从之后创建的文档传递到之前创建的文档



在我的注册请求中,我使用基于两个不同模式的创建两个文档(在单独的集合中(:用户模型和客户端模型。对于上下文,客户端将是一个引用多个用户数组的对象。

用户方案包括"clientID"字段,该字段应包含用户的客户端_id。同样,客户端的"users"字段将包括一个附加的users数组。后者工作正常。

注册时,我先创建一个用户,然后创建一个客户端。我能够通过用户_id到客户端的用户数组中没有问题。但是,我如何获得客户的_id输入用户的clientID字段?

下面的代码错误地说:在初始化之前无法访问"客户端"-我理解为什么会发生这种情况是因为代码的顺序。

但是,我如何使我的代码得到回报,以便我可以添加客户端_id到用户的clientID字段?我确信这是一个常见的问题,但我在Mongoose的文档中找不到相关的文档。

如果有人能帮忙?非常感谢!

module.exports.signup = async (req, res) => {
// extract data from the req.body
const { email, password, fName, lName, companyName, teams } = req.body;
try {
// create a new user on the User model
const user = await User.create({
email: email,
password: password,
clientID: client._id,
});
// create a new client on the Client model
const client = await Client.create({
companyName: companyName,
users: user._id,
});
res.status(201).json(user);
} catch (err) {
const errors = handleErrors(err);
res.status(400).json(errors);
}
};

您可以在创建客户端并稍后引用它时,为客户端使用特定的objectId

只需复制整个代码:

const {ObjectID} = require('mongodb');
module.exports.signup = async (req, res) => {
// extract data from the req.body
const { email, password, fName, lName, companyName, teams } = req.body;
try {
const clientId = ObjectID();
// create a new user on the User model
const user = await User.create({
email: email,
password: password,
clientID: clientId,
});
// create a new client on the Client model
const client = await Client.create({
companyName: companyName,
users: user._id,
_id: clientId
});
res.status(201).json(user);
} catch (err) {
const errors = handleErrors(err);
res.status(400).json(errors);
}
};

另一个解决方案是,您可以在不使用clientId的情况下创建user,并且在创建client之后,您可以使用创建的client.id:更新user

const user = await User.create({
email: email,
password: password,
// clientID: clientId,
});
// create a new client on the Client model
const client = await Client.create({
companyName: companyName,
users: user._id,
});
user.clientId = client._id;
await user.save();