努力从Node.js向users表添加类型值
我有一个问题 我在MongoDB中导入了两个表,其中一个表的用户名包含用户的所有数据,并且有一个名为“type”的条目,该条目链接到另一个名为usertypes的表,该表保存type_id的值(这应该与user表中的type字段相匹配)然后是描述,用于在用户表中定义用户类型 我正在尝试循环node.js中的user表,并分配一个type_id=type表的实际对象id的值,其中users中的type等于usertypes表中的type_id。我添加了两张桌子的图片以供参考 这是我的代码,它不工作…不知道如何从node.js后端进行更新 非常感谢您的帮助努力从Node.js向users表添加类型值,node.js,reactjs,mongodb,Node.js,Reactjs,Mongodb,我有一个问题 我在MongoDB中导入了两个表,其中一个表的用户名包含用户的所有数据,并且有一个名为“type”的条目,该条目链接到另一个名为usertypes的表,该表保存type_id的值(这应该与user表中的type字段相匹配)然后是描述,用于在用户表中定义用户类型 我正在尝试循环node.js中的user表,并分配一个type_id=type表的实际对象id的值,其中users中的type等于usertypes表中的type_id。我添加了两张桌子的图片以供参考 这是我的代码,它不工作
// @route POST api/user_types
// @desc Add User Types
// @access Public
router.post('/', async (req, res) => {
try {
const usertypes = await UserTypes.find();
const users = await User.find();
const combined = { usertypes, users };
const {
type_id,
user_id,
firstname,
lastname,
email,
company_name,
time,
date,
timeslot,
squad_id,
type,
} = req.body;
const linkFields = {
users: req.body.type_id,
user_id,
firstname,
lastname,
email,
company_name,
time,
date,
timeslot,
squad_id,
type,
};
const updatedType = { type_id };
for (const [key, value] of Object.entries(usertypes.type_id)) {
if (usertypes.type_id === users.type)
users.type_id[key] = (value, { usertypes: usertypes.type_id });
}
linkFields.type_id = updatedType;
let updateUser = await User.findOneAndUpdate(
{ users: req.users.type_id },
{ $set: linkFields },
{ new: true, upsert: true, setDefaultsOnInsert: true }
);
res.json(updateUser);
} catch (error) {
console.error(error.message);
res.status(500).send('Server Error');
}
});
如果userTypes
Manager
更改,会发生什么情况?您会更新引用此特定用户类型的每个记录吗?通常,您会引用外部文档的字符串ObjectID,并根据需要填充该数据。在这方面,Mongoose之类的东西可能会有所帮助,因为您可以定义一个模式,该模式具有对其他集合/模式的“引用”。另外,该语法对于设置值users是不正确的。请键入\u id[key]
。您的意思可能类似于users.type_id[key]={…value,usertypes:usertypes.type_id}
,例如获取value
的所有属性并添加usertypes
。