B
B
bro-dev2018-03-05 00:36:38
JavaScript
bro-dev, 2018-03-05 00:36:38

Why does a model with a Number field accept and store a string there?

Here is such a model, we write there and put a string in the id and then the string is written to the database

spoiler
new Schema({
    id: {
        type: Number,
        unique: true,
    }
});

then I try to get this document and not in any
spoiler
User.findOne({ id: 123}) 
User.findOne({ id: "123"})

both of these queries will return null, while if initially written as a number, then it looks for norms in both options.
How to make it strictly so that only the number is written? , I thought that type: Number is enough, it turns out not.
Moreover, if such requests are made through mongo, then everything works fine, that is, User.findOne({ id: "123"}) finds it, but User.findOne({ id: 123}) does not, which is generally true.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Artyom Novolodsky, 2018-03-05
@Tmch

instead of User.findOne({ where: {id: 123}) ?

D
dmitrygavrish, 2018-03-05
@dmitrygavrish

You can try adding validation mongoosejs.com/docs/validation.html :

new Schema({
    id: {
        type: Number,
        unique: true,
        validate: {
          validator: value => typeof value === 'number',
          message: 'Invalid id type'
        },
    }
});

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question