Home > Software design >  mongodb convert data to string. how to fix?
mongodb convert data to string. how to fix?

Time:01-15

I want to get data from my database to work with variables.

Here is my database query:

db.progress.find({username:socket},function(err,res){

what do I get information on:

[ { _id: 61e180b54e0eea1454f8e5e6,
    username: 'user',
    exp: 0,
    fraction: 'undf'} ]

if i send a request

db.progress.find({username:socket},{exp:1},function(err,res){

then in return I will get

[ { _id: 61e180b54e0eea1454f8e5e6, exp: 0 } ]

how do i extract only 0 from the received data. I would like to do something like this.

var findprogress = function(socket,cb){
db.progress.find({username:socket},function(err,res){
cb(res.exp,res.fraction)
})
}



findprogress(socket,function(cb){
console.log(cb.exp)//0
console.log(cb.fraction)//undf
           })

but I don't know how to implement it correctly.

CodePudding user response:

I recommend aggregate in this case so you can more easily manipulate your projected data. For example:

db.progress.aggregate([
{ $match: { username: socket } },
{ $project: { _id: 0, exp: 1 } }
])

This way you directly tell the query to not include the objectId, which is typically included by default.

CodePudding user response:

Try to give 0 to _id:

db.progress.find({username:socket},{exp:1 , _id:0},function(err,res){
  •  Tags:  
  • Related