0

I just stumbled over views in MongoDB and was wondering, if it is in principle possible to create a user depedent view. For example, his user setting from a User_Settings collection.

For the view I came up with the following code, which works fine, as long as the user name is known beforehand:

[
   { 
        "$match" :
        { 
            "name" : "test"
        }
    }
], 
{ 
    "allowDiskUse" : false
}

The current user name is accessible by:

var currentUser = db.runCommand({connectionStatus: 1}).authInfo.authenticatedUsers[0].user

But I could not manage to find out how to merge those two into a coherent view definition. I tried like so, which is obiously not working:

    "$let" :
    {
        vars: {currentUser: {connectionStatus: 1}},
        in: {connectionStatus: 1}
    }
    { 
        "$match" :
        { 
            "name" : currentUser
        }
    }
], 
{ 
    "allowDiskUse" : false
}

Is this at all possible? If so, I would be very grateful if somebody could provide an example.

Thank you

Thor
  • 31
  • 2

1 Answers1

0

const MongoClient = require('mongodb').MongoClient;

const mongo_uri = `mongodb://${settings.database.host}:${settings.database.port}`;
// use it for setup
const MongoClient = require('mongodb').MongoClient;
const settings = require('./settings');
const mongo_uri = `mongodb://${settings.database.host}:${settings.database.port}`;
const bcrypt = require('bcrypt');

const saltRounds = 10;

const user = {
  username: 'adam',
  password: 'password'
};

MongoClient.connect(mongo_uri, { useNewUrlParser: true })
.then(client => {
  const db = client.db('project');
  const collection = db.collection('users');
  bcrypt.genSalt(saltRounds, (error, salt) => {
    bcrypt.hash(user.password, salt, (error, hash) => {
      user.password = hash;
      collection.insertOne(user)
        .then(() => console.log('User inserted'))
        .catch(error => console.error(error));
    });
  });
}).catch(error => console.error(error));