How to check if attribute exists in mongodb document for forEach function?

I am using MongoDB 2.6.2. I need to check forEachif a field nameexists in the selected document.

db.testData.find(...).forEach(function(x){
// insert code here
})

How to check inside a forEachfunction if it xcontains a field nameor not?

+4
source share
1 answer

Mongo shell is a JavaScript shell, so most standard JavaScript methods are supported. You can check if there is a property that you would do on any normal object in JavaScript - using the hasOwnProperty () method :

db.testData.find({}).forEach(function(x){
    if (x.hasOwnProperty('name')) {
        // Do something
    }
})
+6
source

Source: https://habr.com/ru/post/1545231/


All Articles