Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
130 views
in Technique[技术] by (71.8m points)

node.js - nodejs mongodb don't wait the update

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...