I have a problem with my mongoDB script
It looks like that :
const mongodb = require("mongodb").MongoClient;
const class = 'Com'
const a = [{name: 'John', tempData: 'test'}, {name: 'Marie', tempData: 'test'}, {name: 'Luc', tempData: 'test'}]
mongodb.connect(
'mongodb://localhost:27017/', {
useNewUrlParser: true,
useUnifiedTopology: true
},
async (err, client) => {
a.map(async (item) => {
let e = await client.db('project').collection('persons').findOne({
class: class
});
if (!e.students) {
_.set(e, 'students', [item])
}else{
const findData = item.name
const d = await _.find(e.students, findData )
if(!_.isUndefined(d)){
const z = _.indexOf(e.students,d)
e.representants[z] = _.merge(e.students[z],item)
}else{
console.log('Other case')
e.students.push(item)
}
console.log('new object : ',e.students)
}
await client.db('project').collection('persons').findOneAndUpdate({class: class}, {$set: e}, {returnNewDocument: true}, () => {
console.log('Updated')
});
});
});
My problem is that in my first loop, my e
should not have students array, and in the second loop, it should find the same object with the students array, but mongo return the old object, without array, like it has not the time to update the object in database before second loop
I think it's a time problem because my three logs 'Updated' appear after the three 'new object' log, like this :
new object : [{...}]
new object : [{...}]
new object : [{...}]
Updated
Updated
Updated
But it shoud be like this :
new object : [{...}]
Updated
new object : [{...},{...}]
Updated
new object : [{...},{...},{...}]
Updated
I've already try to add promise but it does not work, but maybe i've add it at the wrong line
If u have the solution, it'll save me couple of hours
Thanks in advance
question from:
https://stackoverflow.com/questions/65916152/nodejs-mongodb-dont-wait-the-update