nomadev95
nomadev95

Reputation: 125

Assign value to a NodeJS variable with respect to MongoDB document array

I have a MongoDB collection with the following documents

> db.mycol.find()
{ "_id" : ObjectId("5ec6506171ae442136aa97d2"), "uname" : "mail1", "port" : 1000, "abc" : "test1" }
{ "_id" : ObjectId("5ec659e6c0b1cc11370d8378"), "uname" : "mail2", "port" : 1001, "abc" : "test2" }

In the below code I am trying to fetch an array of document field port by making use of distinct in NodeJS.

var nextPort=0;
MongoClient.connect(url, function(err, db) {
    if (err) throw err;
    var dbo = db.db("mydb");
    dbo.collection("mycol").distinct('port', function(err, result) {
      if (err) throw err;
      console.log(result);
      db.close();
    });
  });

The above code gives an output [ 1000, 1001 ] Now, I have a variable called nextPort I want it to have the next value of already existing ports (should be unique and unused) i.e. if the last element of the array is 1001 then nextPort=1002.

How do I assign the next value (unique) from the array elements to my variable. Also is there a way to have all unique values in the document field port like we have primary key in MySQL

Upvotes: 0

Views: 328

Answers (1)

Stephan Du Toit
Stephan Du Toit

Reputation: 849

Not sure if this will help but you can try assigning the output to a variable, say "array". Then use nextPort = array[array.length-1]+1 See code sample below:

let nextPort=0; 
let arr = [1000, 1001];
nextPort = arr[arr.length-1]+1

or if you want to make nextPort an array:

let nextPort=[]; 
let arr = [1000, 1001];
nextPort.push(...arr, arr[arr.length-1]+1);

The code above assumes your Mongo code will always return a number.

Upvotes: 1

Related Questions