user3703539
user3703539

Reputation: 437

Mongoose not accept number begin with 0

I try to save a french number phone, ex : 060908...

This is my body request :

newAppointment.phone = req.body.phone;

My schema :

phone: {
            type:Number,
            required: true
        }

and my data : 06

This return me an error : SyntaxError: Unexpected number. When i convert it to string it's remove the 0.

Answer : Use STRING.

Upvotes: 1

Views: 2383

Answers (3)

Bez
Bez

Reputation: 69

It's possible to use a get / set mechanism if you really wish to store a phone number as a number. So, your schema could definitely insert a phone number into a number, however, the set would convert the string into a number, by simply removing the leading 0, and then the get, could convert the number into a string, placing the leading 0 back in front.

phone: { type: Number, get: v => v.slice(1)*1, set: v => '0'+v.toString() }

toJSON: { getters: true };

Upvotes: 0

Simran
Simran

Reputation: 2810

If you want 0 at first place. You have to take phone type as string in your schema because we know placing 0 at first place will not change the number's value

so, your schema is like:

phone: {
      type: String,
      required: true
}

and then sends your data as " 0609084542"

Upvotes: 2

Orelsanpls
Orelsanpls

Reputation: 23515

To store a phone like 0609084542 you cannot use a Number field. Use a String field instead.

phone: {
      type: String,
      required: true
}

I think you need some help about types (String, Number aka Int/Char/Long/Float/Double).

Here you have a stack overflow post speaking about the leading 0 in numbers. Like:

const toto = 0652;

To be known:

const toto = 0652;

is different than

const toto = 652;

is different than

const toto = '0652';

Upvotes: 1

Related Questions