-3

I'm making a courier system, in which one franchise needs to dispatch a package to another franchise. User inputs the name of the franchise the package needs to go & I'm fetching the ID & storing in "dispatchedTo". While I'm getting the ID of "dispatchedBy", from Angular localStroage where I saved it when the user(Franchise) logged into the system. But findById, findOne or even find are not working when applied on attributes fetched from localStorage.

    //This Part Does not return franchise... franchise object is empty
    let franchise = await Franchise.findById(req.body.dispatchedBy);
        if(!franchise){
            return res.json({error: {message: "Origin Not Found!"},});
        }
    //This part work... franchise1 is the right object
        let franchise1 = await Franchise.findById(req.body.dispatchedTo);
        if(!franchise1){
            return res.json({error: {message: "Destination Not Found!"},});
        }

MongoDB saves the record with ID of both 'dispatchedBy' & 'dispatchedTo': {"_id":"5c1fdcd0dc5ce60e8c856ca1","dispatchedBy":"5c1c06c2f458b617506f1ac1","dispatchedTo":"5c1de40419975e0a6c224d6a","dispatchedOn":"2018-12-23T19:03:50.997Z","receivedOn":"2018-12-23T19:03:50.997Z","packet":"5c1ea84ca706ba112c9dbe9e","dispatchStatus":"DisJanu","user":"Sohail","__v":0}

However, when I apply populate then 'dispatchedBy' returns null.

router.get('/', async(req, res)=>{
const dispatch = await Dispatch.find().sort('dispatchedOn').populate('packet', 'packetNumber _id').populate('dispatchedBy', 'title _id').populate('dispatchedTo', 'title _id');
return res.json(dispatch);

});

Any possible fix?

1 Answers1

0

So findById just filters only on the basis of the _id field. You can try findOne like

Franchise.findOne({ dispatchedBy: req.body.dispatchedBy });
Franchise.findOne({ dispatchedTo: req.body.dispatchedTo });
Nimish Gupta
  • 971
  • 7
  • 17
  • Nimish! I've tried findOne as well, returns null. I'm fetching dispatchedBy from localStorage, and findOne, find or findbyId is not working with dispatchedBy. I tried this: store username & password of a user in localStorage then try to authenticate by retrieving username & password from localStorage & again mongoose is unable to find the user. It must be Angular localStorage, I'm pulling my hair now. – Sohail Jaffry Dec 23 '18 at 21:14
  • Hey Nimish! I'v found the issue. I was logged in as a user with different role :( I was logged in as Admin instead of Franchise :( – Sohail Jaffry Dec 23 '18 at 21:30