imported some fixes from mongoose upstream