0

Am having issues with converting object value from Number to String in mongodb using mongoose, if I try to change it to a String type it saves without having any errors, but when I console.log typeof saved data it still shows Number. Also if I change the value to a string it turns to a string e.g st.bankaccnum = "you are" it throws error,(Cast to Number failed). But users data are already stored in database and I would like to turn everything to a String type.

User.find({bankaccname: {$exists: 1}}, function(err,user){
    user.forEach(function(st){
        let num = st.bankaccnum;
        st.bankaccnum = new String(st.bankaccnum);
        st.save(function(err,saved){
            if(err){
                console.log(err)
            } else {console.log(typeof saved.bankaccnum)}
        })
    })
})
Fillipo Sniper
  • 419
  • 2
  • 11
  • 28
  • My userSchema for the number is saved as {bankaccnum: {type: Number}} – Fillipo Sniper May 16 '19 at 13:06
  • what's the problem here? are you getting any errors ? – Vikash_Singh May 16 '19 at 13:10
  • Is the above script not working for you? Try doing this : `st.bankaccnum = ""+st.bankaccnum;` – Vikash_Singh May 16 '19 at 13:11
  • @VikashSingh am not getting any errors, but after it saves typeof is still a number and it's still in number format when I view it in the database, so which means it's not being converted to a number. – Fillipo Sniper May 16 '19 at 13:14
  • I have done that before, but it still gives same result of a number type. – Fillipo Sniper May 16 '19 at 13:15
  • 1
    This is normal no? If your mongoose schema defines "bankaccnum" as a Number type, then you won't be able to put anything else than string representation of a number or a number . I guess mongo is able to auto-cast a string to a number when its possible so that's why when you enter "you are" it obviously cannot be casted. – Flo May 16 '19 at 15:29
  • By the way, that post may help you converting existing values to a new type : https://stackoverflow.com/questions/4973095/mongodb-how-to-change-the-type-of-a-field . Hope it helps. – Flo May 16 '19 at 15:40
  • Then don't use `.save` instead please use `update` with `$set` to update that field. This will definitely work. – Vikash_Singh May 16 '19 at 18:55

0 Answers0