简体   繁体   中英

node, mongoose 'findOne' on one collection inside 'find' of another collection

Basically i have simple scenario, first i need to fetch whole collection, for example "cars" then iterate through that collection and execute 'findOne' on some another collection, for example "users" based on some condition from first collection.

So:

// requiring modules and mongoose.connect() part
...
CarModel.find(function(err, cars) {

    console.log("1");

    _.each(cars, function(car) {

        console.log("2");

        UserModel.findOne({username: car.owner}, function(err, user) {
            console.log("3");

            user.some_field++;
            user.save();
        });
    });
});

For example when cars collection has 2 documents(same car.owner) im expecting 2 increments for 'some_field' but i get only one.

// console.logs
1
2
2
3
3

I can guess that im doing something wrong here with flow of execution and asynchronous stuff, can someone explain me why this is not woriking.

findOne is async so the callbacks for both owners' findOne result can be queued up to run where user.some_field for both have the same initial value. Each callback then runs and saves the new value as the initial value plus 1.

This is the classic case for why you want to use an update with the atomic $inc operator instead.

UserModel.findOneAndUpdate({username: car.owner}, {$inc: {some_field: 1}},
    function(err, numAffected) { ... }
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM