node.jsfluttermongodbexpress

The factory._id cant be added inside the user table using node.js and MongoDB


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 I can add the user even though the factory ID is not detected 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


Solution

  • Sorry for my recklessness, it seems like the problem is that in the dart file, in this line 'factories': widget.factory.factoryId, it supposed to be factoryId as I already declared that in here const { phoneNumber, factoryId } = req.body;