I have looked every where and can not find whether it can be done I'm trying to return all values in a object by only searching by it's key name. My document looks like this.
{
"_id": ObjectID("5636e00c09431db4560ef063"),
"username": "example@web.com",
"credentials": {
"password": "e5e0ba4ce8ae13d1d0291e98d9a62b4d68f1db737a36a9373f916185157500cc",
"randomSalt": "00dfb37635ba7e5a513f9fd6e8bdf746f85ec3571df8288e1fdb44f399e331f0"
}
}
Is there a fast easy way in doing this with the native node.js drivers
My code so far
function getUserLoginFromDatabase(username, callback) {
mongodb.connect(url, function(err, db) {
if(err) {
callback(err);
db.close();
return;
}
var collection = db.collection(username);
collection.find({},{"credentials":1}, function(err, result) {
console.log(result);
callback(err, result);
db.close();
});
});
};
Update Going off of what Alok Deshwal said to do i get this. I'm using mongodb v3.0.7 if that makes a difference.
function getUserLoginFromDatabase(username, callback) {
mongodb.connect(url, function(err, db) {
if(err) {
callback(err);
db.close();
return;
}
var collection = db.collection(username);
collection.find({},{"credentials":1,"_id":0,"username":0}, function(err, result) {
console.log(result);
callback(err, result);
db.close();
});
});
};
Output
Readable {
connection: null,
server: null,
disconnectHandler:
{ s: { storedOps: [], storeOptions: [Object], topology: [Object] },
length: [Getter] },
bson: {},
ns: 'mydb.exsample@web.com',
cmd:
{ find: 'mydb.exsample@web.com',
limit: 0,
skip: 0,
query: {},
slaveOk: true,
readPreference: { preference: 'primary', tags: undefined, options: undefined },
fields: { credentials: 1, _id: 0, username: 0 } },
options:
{ skip: 0,
limit: 0,
raw: undefined,
hint: null,
timeout: undefined,
slaveOk: true,
readPreference: { preference: 'primary', tags: undefined, options: undefined },
db:
EventEmitter {
domain: null,
_events: {},
_eventsCount: 0,
_maxListeners: undefined,
s: [Object],
serverConfig: [Getter],
bufferMaxEntries: [Getter],
databaseName: [Getter],
options: [Getter],
native_parser: [Getter],
slaveOk: [Getter],
writeConcern: [Getter] },
promiseLibrary: [Function: Promise],
disconnectHandler: { s: [Object], length: [Getter] } },
topology:
EventEmitter {
domain: null,
_events:
{ reconnect: [Function],
timeout: [Object],
error: [Object],
close: [Function],
destroy: [Object] },
_eventsCount: 5,
_maxListeners: undefined,
s:
{ options: [Object],
callbacks: [Object],
logger: [Object],
state: 'connected',
reconnect: true,
reconnectTries: 30,
reconnectInterval: 1000,
emitError: true,
currentReconnectRetry: 30,
ismaster: [Object],
readPreferenceStrategies: undefined,
authProviders: [Object],
id: 1,
tag: undefined,
disconnectHandler: [Object],
wireProtocolHandler: {},
Cursor: [Object],
bsonInstance: {},
bson: {},
pool: [Object],
serverDetails: [Object] },
name: [Getter],
bson: [Getter],
wireProtocolHandler: [Getter],
id: [Getter] },
cursorState:
{ cursorId: null,
cmd:
{ find: 'mydb.exsample@web.com',
limit: 0,
skip: 0,
query: {},
slaveOk: true,
readPreference: [Object],
fields: [Object] },
documents: [],
cursorIndex: 0,
dead: false,
killed: false,
init: false,
notified: false,
limit: 0,
skip: 0,
batchSize: 1000,
currentLimit: 0,
transforms: undefined },
callbacks: null,
logger: { className: 'Cursor' },
_readableState:
ReadableState {
objectMode: true,
highWaterMark: 16,
buffer: [],
length: 0,
pipes: null,
pipesCount: 0,
flowing: null,
ended: false,
endEmitted: false,
reading: false,
sync: true,
needReadable: false,
emittedReadable: false,
readableListening: false,
defaultEncoding: 'utf8',
ranOut: false,
awaitDrain: 0,
readingMore: false,
decoder: null,
encoding: null },
readable: true,
domain: null,
_events: {},
_eventsCount: 0,
_maxListeners: undefined,
s:
{ numberOfRetries: 5,
tailableRetryInterval: 500,
currentNumberOfRetries: 5,
state: 0,
streamOptions: {},
bson: {},
ns: 'mydb.exsample@web.com',
cmd:
{ find: 'mydb.exsample@web.com',
limit: 0,
skip: 0,
query: {},
slaveOk: true,
readPreference: [Object],
fields: [Object] },
options:
{ skip: 0,
limit: 0,
raw: undefined,
hint: null,
timeout: undefined,
slaveOk: true,
readPreference: [Object],
db: [Object],
promiseLibrary: [Function: Promise],
disconnectHandler: [Object] },
topology:
EventEmitter {
domain: null,
_events: [Object],
_eventsCount: 5,
_maxListeners: undefined,
s: [Object],
name: [Getter],
bson: [Getter],
wireProtocolHandler: [Getter],
id: [Getter] },
topologyOptions:
{ socketOptions: {},
auto_reconnect: true,
host: 'localhost',
port: 27017,
cursorFactory: [Object],
reconnect: true,
emitError: true,
size: 5,
disconnectHandler: [Object],
bson: {},
messageHandler: [Function],
wireProtocolHandler: {} },
promiseLibrary: [Function: Promise],
currentDoc: null },
timeout: false,
sortValue: undefined,
readPreference: { preference: 'primary', tags: undefined, options: undefined } }
You can do something like this in order to get existing credentials only.
var res = []; db.collection.find({credentials : {$exists:true}}).forEach(function(document){ res.push(document.credentials})
Then you can callback the array: callback(err, res)
Does this help you?
Alright so based on what i original thought was the right way i can achieve my output by throwing it into a array. You only need "credentials":1
to only grab the credentials and including "credentials":1,"_id":0,"username":0
as told by Alok Deshwal causes mongodb to throw a error.
function getUserLoginFromDatabase(username, callback) {
mongodb.connect(url, function(err, db) {
if(err) {
callback(err);
db.close();
return;
}
var collection = db.collection(username);
collection.find({},{"credentials":1}).toArray(function(err, result) {
callback(err, result);
db.close();
});
});
};
But then it becomes tedious in the callback to use the data because it is in a array when it should not be. I'll be asking another question about this and also why including more fields causes mongodb to throw a error.
randomSalt = result[0]["credentials"].randomSalt;
userStoredPassword = result[0]["credentials"].password;
Also the conclusion of this answer is here
If you want to search by it's key name , you can use $exist operator
db.collection.find({},{"credentials":1,"_id":0,"username":0})
use "keyname":0
to exclude from result and "keyname":1
to include in result
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.