简体   繁体   中英

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) ie 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

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.

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