How to search and update data with mongoose?

0

I'm using mongodb with mongoose in nodejs, I have my schema like this:

const UserSchema = new mongoose.Schema({
    username: {
        type: String,
        unique: true,
        require: true
    },
    balances: {
        dolar: {
            manualBalance: {
                type: Number,
                select: false
            },
            paidBalance: {
                type: Number,
                select: false
            }
        }
    }

});

I try to do this:

router.post('/get_user_balance', async (req, res) => {
    const { username } = req.body;
    User.findOneAndUpdate({ username: username }, { $set: { balances: {dolar: {manualBalance: '1.50' }}}});
        const balances = await User.findOne({ username }).select('+balances.dolar.manualBalance');
        console.log(balances);
}

and I get the nodejs error:

(node:22826) UnhandledPromiseRejectionWarning: MongoError: Projection cannot have a mix of inclusion and exclusion.

I believe it is% w / o% wrong. So I also tried without the select and I removed the "select: false" from my schema, I resisted the database and re-created a user, and I receive only the username from console.log, instead of also receiving the "balances" field. p>

{
  _id: 5ab00b7a92fe402bb85f407f,
  username: 'Jerildo',
  __v: 0
}

I'm registering users like this:

const user = await User.create(req.body);

where req.body is: .select('+balances.dolar.manualBalance');

I know it must be simple thing that I'm missing out on not knowing mongodb or mongoose so well, I've always worked with Redis, this is new here for me. So I ask for a force here.

    
asked by anonymous 20.03.2018 / 00:22

1 answer

1

As quoted in the comments:

  

I do not know why you're using async ...

While using async , you should wait (await) both on the first request (findOneAndUpdate ()) and on the second (findOne ()) which you are already doing.

By default the function findOneAndUpdate() returns the original document, if you want to return the modified document you must pass an argument in the example option object:

User.findOneAndUpdate({}, {}, {new: true})

Imagining that you have created a document, then the following example:

await User.findOneAndUpdate({
    username: 'Jerildo'
}, {
    $set: {
        balances: {
            dolar: {
                manualBalance: '1.50'
            }
        }
    }
}, {
    new: true // retorna o novo objeto
})

const balances = await User.findOne({ username: 'Jerildo' }).select('+balances.dolar.manualBalance')
console.log(balances)

Will return the modified document (in console.log ())

Optionally you can chain the response (result) of findOneAndUpdate() lgo as:

await USER.findOneAndUpdate({
    username: 'Jerildo'
}, {
    $set: {
        balances: {
            dolar: {
                manualBalance: '1.50'
            }
        }
    }
}, {
    new: true // retorna o novo objeto
}, (err, doc) => {
    if ( err ) {
        console.error(err)
    }
    // o documento com o novo valor (atulizado)
    console.log(doc)
})

NOTE: I set username to this example, you should check (validate) your request schema to ensure there is a username .

    
20.03.2018 / 02:06