0
I’m studying the framework Express to create a REST and when writing afunction I am unable to return the value that was processed.
When making the call to endpoint /test, the code below is executed:
app.get('/test', (req, res) => {
const value = getNextSequenceValue('cursoId');
console.log(value);
res.json(value);
});
So the function getNextSequenceValue runs the logic below:
function getNextSequenceValue(sequenceName) {
let returnNextValue = 0;
MongoClient.connect(url, { useUnifiedTopology: true }, (err, client) => {
//defini o banco de dados como 'test'
const db = client.db('test');
//verificar se a coleção 'counters' existe no banco de dados 'test'
//se não existir, cria a coleção 'counters' no banco de dados 'test'
db.listCollections({ name: 'counters' }).toArray((err, result) => {
if (err) {
throw 'error in list collections';
};
if (result.length == 0) {
db.createCollection('counters');
};
});
//defini a coleção como 'counters'
const collection = db.collection('counters');
//verifica se na coleção 'counters' existe um documento com o 'id' igual a variavel 'sequenceName'
//se não existir cria o documento, com o valor da sequenciaValue = 0
collection.findOne({ id: sequenceName }).then(result => {
if (!result) {
collection.insertOne({
id: sequenceName,
sequenceValue: 0
});
};
}).catch(err => console.log(err));
//incremente a sequenciaValue em 1 do id passado.
collection.findOneAndUpdate(
{ id: sequenceName },
{ $inc: { sequenceValue: 1 } },
{ 'returnNewDocument': true }
)
.then(result => {
console.log(result.value.sequenceValue);
returnNextValue = result.value.sequenceValue;
})
.catch(err => console.log(err))
.finally(() => client.close());
});
return returnNextValue;
};
As can be seen in the excerpt:
.then(result => {
console.log(result.value.sequenceValue);
returnNextValue = result.value.sequenceValue;
})
Console output is correct, logic checks the required stock and displays on the console the value of the next sequence.
However, I cannot assign this value to the variable returnNextValue, soon the return is being 0.
Already tried leaving the getNextSequenceValue function as async and calling it with await in the express API?
– Daniel Mendes
no =/, I will search on that. thank you
– Thomas Erich Pimentel