I’m new to the node.js and express.js. I’m building a flutter app where i can add the phone number that I want to invite in my database. With adding the phone number inside the database, it will also add the factories id that it assign to. for example, if i clicked the add button in factory one, the objectId of the factory should be returned. But the problem is, the user will be added without any factories id assign to it, even though it is the same as objectId.
this is my controller snippet for it
exports.inviteEngineer = async (req, res) => {
const { phoneNumber, factoryId } = req.body;
try {
let user = await User.findOne({ phoneNumber });
if (!user) {
user = new User({ phoneNumber, invited: true });
} else {
user.invited = true;
}
let factory = await Factory.find({_id: factoryId});
if (!factory) {
return res.status(404).json({ message: 'Factory not found'});
}
if (!user.factories.includes(factory._id)) {
user.factories.push(factory._id);
}
if (!factory.engineers.includes(user._id)) {
factory.engineers.push(user._id);
}
await user.save();
await factory.save();
res.status(200).json({ message: 'Engineer invited successfully' });
} catch (error) {
res.status(500).json({ error: error.message });
}
};
this are my routes
router.post('/register', registerUser);
router.post('/verify-otp', verifyOtp);
router.post('/invite-engineer', protect, inviteEngineer);
router.get('/protected', protect, (req, res) => {
res.status(200).json({ message: 'This is a protected route' });
});
model of my factory
Factory(
factoryId: '668637b5a5d082f6188137d4',
factoryName: "Factory 4",
status: "⚠️ XYZ6666 IS UNREACHABLE!",
steamPressure: 0.0,
steamFlow: 0.0,
waterLevel: 0.0,
powerFrequency: 0.0,
datetime: "--:--",
engineers: [
Engineer(name: "Noname", phone: "+6014123458"),
],
threshold: Threshold(
steamPressure: 20,
steamFlow: 20,
waterLevel: 20,
powerFrequency: 20,
),
),
this is my dart file snippet
Future<void> addNewEngineer() async {
String name = nameController.text.trim();
String phone = phoneNumberController.text.trim();
if (name.isNotEmpty && phone.isNotEmpty) {
final prefs = await SharedPreferences.getInstance();
final String? token = prefs.getString('token');
if (token != null) {
final response = await http.post(
Uri.parse('my-api'), //i have my actual api here
headers: <String, String>{
'Content-Type': 'application/json; charset=UTF-8',
'Authorization': 'Bearer $token',
},
body: jsonEncode(<String, String>{
'phoneNumber': phone,
'factories': widget.factory.factoryId,
}),
);
if (response.statusCode == 200) {
setState(() {
widget.factory.engineers.add(Engineer(name: name, phone: phone));
nameController.clear();
phoneNumberController.clear();
});
Navigator.of(context).pop();
} else {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text('Failed to add user: ${response.statusCode}')),
);
}
} else {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('Authentication token not found')),
);
}
} else {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('Please enter all fields')),
);
}
}
mongodb screenshot
enter image description here
i know the reason because i can add the user even though the factory id are not detect is because of the body part in that dart file.
I have try to change the id from string to object id but the result is still the same
Shin is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.