id
int32
0
58k
repo
stringlengths
5
67
path
stringlengths
4
116
func_name
stringlengths
0
58
original_string
stringlengths
52
373k
language
stringclasses
1 value
code
stringlengths
52
373k
code_tokens
sequence
docstring
stringlengths
4
11.8k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
86
226
6,400
deepstreamIO/deepstream.io
src/record/record-handler.js
sendRecord
function sendRecord (recordName, record, socketWrapper) { socketWrapper.sendMessage(RECORD, C.ACTIONS.READ, [recordName, record._v, record._d]) }
javascript
function sendRecord (recordName, record, socketWrapper) { socketWrapper.sendMessage(RECORD, C.ACTIONS.READ, [recordName, record._v, record._d]) }
[ "function", "sendRecord", "(", "recordName", ",", "record", ",", "socketWrapper", ")", "{", "socketWrapper", ".", "sendMessage", "(", "RECORD", ",", "C", ".", "ACTIONS", ".", "READ", ",", "[", "recordName", ",", "record", ".", "_v", ",", "record", ".", "_d", "]", ")", "}" ]
Sends the records data current data once done @param {String} recordName @param {Object} record @param {SocketWrapper} socketWrapper the socket that send the request @private @returns {void}
[ "Sends", "the", "records", "data", "current", "data", "once", "done" ]
247aea5e49a94f57f72fbac8e2f4dc0cdbbded18
https://github.com/deepstreamIO/deepstream.io/blob/247aea5e49a94f57f72fbac8e2f4dc0cdbbded18/src/record/record-handler.js#L710-L712
6,401
deepstreamIO/deepstream.io
src/event/event-handler.js
validateSubscriptionMessage
function validateSubscriptionMessage (socket, message) { if (message.data && message.data.length === 1 && typeof message.data[0] === 'string') { return true } socket.sendError(C.TOPIC.EVENT, C.EVENT.INVALID_MESSAGE_DATA, message.raw) return false }
javascript
function validateSubscriptionMessage (socket, message) { if (message.data && message.data.length === 1 && typeof message.data[0] === 'string') { return true } socket.sendError(C.TOPIC.EVENT, C.EVENT.INVALID_MESSAGE_DATA, message.raw) return false }
[ "function", "validateSubscriptionMessage", "(", "socket", ",", "message", ")", "{", "if", "(", "message", ".", "data", "&&", "message", ".", "data", ".", "length", "===", "1", "&&", "typeof", "message", ".", "data", "[", "0", "]", "===", "'string'", ")", "{", "return", "true", "}", "socket", ".", "sendError", "(", "C", ".", "TOPIC", ".", "EVENT", ",", "C", ".", "EVENT", ".", "INVALID_MESSAGE_DATA", ",", "message", ".", "raw", ")", "return", "false", "}" ]
Makes sure that subscription message contains the name of the event. Sends an error to the client if not @param {SocketWrapper} socket @param {Object} message parsed and permissioned deepstream message @private @returns {Boolean} is valid subscription message
[ "Makes", "sure", "that", "subscription", "message", "contains", "the", "name", "of", "the", "event", ".", "Sends", "an", "error", "to", "the", "client", "if", "not" ]
247aea5e49a94f57f72fbac8e2f4dc0cdbbded18
https://github.com/deepstreamIO/deepstream.io/blob/247aea5e49a94f57f72fbac8e2f4dc0cdbbded18/src/event/event-handler.js#L127-L135
6,402
deepstreamIO/deepstream.io
src/permission/config-compiler.js
compileRuleset
function compileRuleset (path, rules) { const ruleset = pathParser.parse(path) ruleset.rules = {} for (const ruleType in rules) { ruleset.rules[ruleType] = ruleParser.parse( rules[ruleType], ruleset.variables ) } return ruleset }
javascript
function compileRuleset (path, rules) { const ruleset = pathParser.parse(path) ruleset.rules = {} for (const ruleType in rules) { ruleset.rules[ruleType] = ruleParser.parse( rules[ruleType], ruleset.variables ) } return ruleset }
[ "function", "compileRuleset", "(", "path", ",", "rules", ")", "{", "const", "ruleset", "=", "pathParser", ".", "parse", "(", "path", ")", "ruleset", ".", "rules", "=", "{", "}", "for", "(", "const", "ruleType", "in", "rules", ")", "{", "ruleset", ".", "rules", "[", "ruleType", "]", "=", "ruleParser", ".", "parse", "(", "rules", "[", "ruleType", "]", ",", "ruleset", ".", "variables", ")", "}", "return", "ruleset", "}" ]
Compiles an individual ruleset @param {String} path @param {Object} rules @private @returns {Object} compiledRuleset
[ "Compiles", "an", "individual", "ruleset" ]
247aea5e49a94f57f72fbac8e2f4dc0cdbbded18
https://github.com/deepstreamIO/deepstream.io/blob/247aea5e49a94f57f72fbac8e2f4dc0cdbbded18/src/permission/config-compiler.js#L42-L54
6,403
deepstreamIO/deepstream.io
src/record/record-request.js
sendError
function sendError ( event, message, recordName, socketWrapper, onError, options, context, metaData ) { options.logger.error(event, message, metaData) if (socketWrapper) { socketWrapper.sendError(C.TOPIC.RECORD, event, message) } if (onError) { onError.call(context, event, message, recordName, socketWrapper) } }
javascript
function sendError ( event, message, recordName, socketWrapper, onError, options, context, metaData ) { options.logger.error(event, message, metaData) if (socketWrapper) { socketWrapper.sendError(C.TOPIC.RECORD, event, message) } if (onError) { onError.call(context, event, message, recordName, socketWrapper) } }
[ "function", "sendError", "(", "event", ",", "message", ",", "recordName", ",", "socketWrapper", ",", "onError", ",", "options", ",", "context", ",", "metaData", ")", "{", "options", ".", "logger", ".", "error", "(", "event", ",", "message", ",", "metaData", ")", "if", "(", "socketWrapper", ")", "{", "socketWrapper", ".", "sendError", "(", "C", ".", "TOPIC", ".", "RECORD", ",", "event", ",", "message", ")", "}", "if", "(", "onError", ")", "{", "onError", ".", "call", "(", "context", ",", "event", ",", "message", ",", "recordName", ",", "socketWrapper", ")", "}", "}" ]
Sends an error to the socketWrapper that requested the record
[ "Sends", "an", "error", "to", "the", "socketWrapper", "that", "requested", "the", "record" ]
247aea5e49a94f57f72fbac8e2f4dc0cdbbded18
https://github.com/deepstreamIO/deepstream.io/blob/247aea5e49a94f57f72fbac8e2f4dc0cdbbded18/src/record/record-request.js#L9-L19
6,404
deepstreamIO/deepstream.io
src/record/record-request.js
onStorageResponse
function onStorageResponse ( error, record, recordName, socketWrapper, onComplete, onError, options, context, metaData ) { if (error) { sendError( C.EVENT.RECORD_LOAD_ERROR, `error while loading ${recordName} from storage:${error.toString()}`, recordName, socketWrapper, onError, options, context, metaData ) } else { onComplete.call(context, record || null, recordName, socketWrapper) if (record) { options.cache.set(recordName, record, () => {}, metaData) } } }
javascript
function onStorageResponse ( error, record, recordName, socketWrapper, onComplete, onError, options, context, metaData ) { if (error) { sendError( C.EVENT.RECORD_LOAD_ERROR, `error while loading ${recordName} from storage:${error.toString()}`, recordName, socketWrapper, onError, options, context, metaData ) } else { onComplete.call(context, record || null, recordName, socketWrapper) if (record) { options.cache.set(recordName, record, () => {}, metaData) } } }
[ "function", "onStorageResponse", "(", "error", ",", "record", ",", "recordName", ",", "socketWrapper", ",", "onComplete", ",", "onError", ",", "options", ",", "context", ",", "metaData", ")", "{", "if", "(", "error", ")", "{", "sendError", "(", "C", ".", "EVENT", ".", "RECORD_LOAD_ERROR", ",", "`", "${", "recordName", "}", "${", "error", ".", "toString", "(", ")", "}", "`", ",", "recordName", ",", "socketWrapper", ",", "onError", ",", "options", ",", "context", ",", "metaData", ")", "}", "else", "{", "onComplete", ".", "call", "(", "context", ",", "record", "||", "null", ",", "recordName", ",", "socketWrapper", ")", "if", "(", "record", ")", "{", "options", ".", "cache", ".", "set", "(", "recordName", ",", "record", ",", "(", ")", "=>", "{", "}", ",", "metaData", ")", "}", "}", "}" ]
Callback for responses returned by the storage connector. The request will complete or error here, if the record couldn't be found in storage no further attempts to retrieve it will be made
[ "Callback", "for", "responses", "returned", "by", "the", "storage", "connector", ".", "The", "request", "will", "complete", "or", "error", "here", "if", "the", "record", "couldn", "t", "be", "found", "in", "storage", "no", "further", "attempts", "to", "retrieve", "it", "will", "be", "made" ]
247aea5e49a94f57f72fbac8e2f4dc0cdbbded18
https://github.com/deepstreamIO/deepstream.io/blob/247aea5e49a94f57f72fbac8e2f4dc0cdbbded18/src/record/record-request.js#L25-L46
6,405
deepstreamIO/deepstream.io
src/record/record-request.js
onCacheResponse
function onCacheResponse ( error, record, recordName, socketWrapper, onComplete, onError, options, context, metaData ) { if (error) { sendError( C.EVENT.RECORD_LOAD_ERROR, `error while loading ${recordName} from cache:${error.toString()}`, recordName, socketWrapper, onError, options, context, metaData ) } else if (record) { onComplete.call(context, record, recordName, socketWrapper) } else if ( !options.storageExclusion || !options.storageExclusion.test(recordName) ) { let storageTimedOut = false const storageTimeout = setTimeout(() => { storageTimedOut = true sendError( C.EVENT.STORAGE_RETRIEVAL_TIMEOUT, recordName, recordName, socketWrapper, onError, options, context, metaData ) }, options.storageRetrievalTimeout) options.storage.get(recordName, (storageError, recordData) => { if (!storageTimedOut) { clearTimeout(storageTimeout) onStorageResponse( storageError, recordData, recordName, socketWrapper, onComplete, onError, options, context, metaData ) } }, metaData) } else { onComplete.call(context, null, recordName, socketWrapper) } }
javascript
function onCacheResponse ( error, record, recordName, socketWrapper, onComplete, onError, options, context, metaData ) { if (error) { sendError( C.EVENT.RECORD_LOAD_ERROR, `error while loading ${recordName} from cache:${error.toString()}`, recordName, socketWrapper, onError, options, context, metaData ) } else if (record) { onComplete.call(context, record, recordName, socketWrapper) } else if ( !options.storageExclusion || !options.storageExclusion.test(recordName) ) { let storageTimedOut = false const storageTimeout = setTimeout(() => { storageTimedOut = true sendError( C.EVENT.STORAGE_RETRIEVAL_TIMEOUT, recordName, recordName, socketWrapper, onError, options, context, metaData ) }, options.storageRetrievalTimeout) options.storage.get(recordName, (storageError, recordData) => { if (!storageTimedOut) { clearTimeout(storageTimeout) onStorageResponse( storageError, recordData, recordName, socketWrapper, onComplete, onError, options, context, metaData ) } }, metaData) } else { onComplete.call(context, null, recordName, socketWrapper) } }
[ "function", "onCacheResponse", "(", "error", ",", "record", ",", "recordName", ",", "socketWrapper", ",", "onComplete", ",", "onError", ",", "options", ",", "context", ",", "metaData", ")", "{", "if", "(", "error", ")", "{", "sendError", "(", "C", ".", "EVENT", ".", "RECORD_LOAD_ERROR", ",", "`", "${", "recordName", "}", "${", "error", ".", "toString", "(", ")", "}", "`", ",", "recordName", ",", "socketWrapper", ",", "onError", ",", "options", ",", "context", ",", "metaData", ")", "}", "else", "if", "(", "record", ")", "{", "onComplete", ".", "call", "(", "context", ",", "record", ",", "recordName", ",", "socketWrapper", ")", "}", "else", "if", "(", "!", "options", ".", "storageExclusion", "||", "!", "options", ".", "storageExclusion", ".", "test", "(", "recordName", ")", ")", "{", "let", "storageTimedOut", "=", "false", "const", "storageTimeout", "=", "setTimeout", "(", "(", ")", "=>", "{", "storageTimedOut", "=", "true", "sendError", "(", "C", ".", "EVENT", ".", "STORAGE_RETRIEVAL_TIMEOUT", ",", "recordName", ",", "recordName", ",", "socketWrapper", ",", "onError", ",", "options", ",", "context", ",", "metaData", ")", "}", ",", "options", ".", "storageRetrievalTimeout", ")", "options", ".", "storage", ".", "get", "(", "recordName", ",", "(", "storageError", ",", "recordData", ")", "=>", "{", "if", "(", "!", "storageTimedOut", ")", "{", "clearTimeout", "(", "storageTimeout", ")", "onStorageResponse", "(", "storageError", ",", "recordData", ",", "recordName", ",", "socketWrapper", ",", "onComplete", ",", "onError", ",", "options", ",", "context", ",", "metaData", ")", "}", "}", ",", "metaData", ")", "}", "else", "{", "onComplete", ".", "call", "(", "context", ",", "null", ",", "recordName", ",", "socketWrapper", ")", "}", "}" ]
Callback for responses returned by the cache connector @private @returns {void}
[ "Callback", "for", "responses", "returned", "by", "the", "cache", "connector" ]
247aea5e49a94f57f72fbac8e2f4dc0cdbbded18
https://github.com/deepstreamIO/deepstream.io/blob/247aea5e49a94f57f72fbac8e2f4dc0cdbbded18/src/record/record-request.js#L54-L104
6,406
deepstreamIO/deepstream.io
src/record/json-path.js
setValue
function setValue (root, path, value) { const tokens = tokenize(path) let node = root let i for (i = 0; i < tokens.length - 1; i++) { const token = tokens[i] if (node[token] !== undefined && typeof node[token] === 'object') { node = node[token] } else if (typeof tokens[i + 1] === 'number') { node = node[token] = [] } else { node = node[token] = {} } } node[tokens[i]] = value }
javascript
function setValue (root, path, value) { const tokens = tokenize(path) let node = root let i for (i = 0; i < tokens.length - 1; i++) { const token = tokens[i] if (node[token] !== undefined && typeof node[token] === 'object') { node = node[token] } else if (typeof tokens[i + 1] === 'number') { node = node[token] = [] } else { node = node[token] = {} } } node[tokens[i]] = value }
[ "function", "setValue", "(", "root", ",", "path", ",", "value", ")", "{", "const", "tokens", "=", "tokenize", "(", "path", ")", "let", "node", "=", "root", "let", "i", "for", "(", "i", "=", "0", ";", "i", "<", "tokens", ".", "length", "-", "1", ";", "i", "++", ")", "{", "const", "token", "=", "tokens", "[", "i", "]", "if", "(", "node", "[", "token", "]", "!==", "undefined", "&&", "typeof", "node", "[", "token", "]", "===", "'object'", ")", "{", "node", "=", "node", "[", "token", "]", "}", "else", "if", "(", "typeof", "tokens", "[", "i", "+", "1", "]", "===", "'number'", ")", "{", "node", "=", "node", "[", "token", "]", "=", "[", "]", "}", "else", "{", "node", "=", "node", "[", "token", "]", "=", "{", "}", "}", "}", "node", "[", "tokens", "[", "i", "]", "]", "=", "value", "}" ]
This class allows to set or get specific values within a json data structure using string-based paths @param {String} path A path, e.g. users[2].firstname @constructor
[ "This", "class", "allows", "to", "set", "or", "get", "specific", "values", "within", "a", "json", "data", "structure", "using", "string", "-", "based", "paths" ]
247aea5e49a94f57f72fbac8e2f4dc0cdbbded18
https://github.com/deepstreamIO/deepstream.io/blob/247aea5e49a94f57f72fbac8e2f4dc0cdbbded18/src/record/json-path.js#L14-L32
6,407
deepstreamIO/deepstream.io
src/record/json-path.js
tokenize
function tokenize (path) { const tokens = [] const parts = path.split('.') for (let i = 0; i < parts.length; i++) { const part = parts[i].trim() if (part.length === 0) { continue } const arrayIndexes = part.split(SPLIT_REG_EXP) tokens.push(arrayIndexes[0]) for (let j = 1; j < arrayIndexes.length; j++) { if (arrayIndexes[j].length === 0) { continue } tokens.push(Number(arrayIndexes[j])) } } return tokens }
javascript
function tokenize (path) { const tokens = [] const parts = path.split('.') for (let i = 0; i < parts.length; i++) { const part = parts[i].trim() if (part.length === 0) { continue } const arrayIndexes = part.split(SPLIT_REG_EXP) tokens.push(arrayIndexes[0]) for (let j = 1; j < arrayIndexes.length; j++) { if (arrayIndexes[j].length === 0) { continue } tokens.push(Number(arrayIndexes[j])) } } return tokens }
[ "function", "tokenize", "(", "path", ")", "{", "const", "tokens", "=", "[", "]", "const", "parts", "=", "path", ".", "split", "(", "'.'", ")", "for", "(", "let", "i", "=", "0", ";", "i", "<", "parts", ".", "length", ";", "i", "++", ")", "{", "const", "part", "=", "parts", "[", "i", "]", ".", "trim", "(", ")", "if", "(", "part", ".", "length", "===", "0", ")", "{", "continue", "}", "const", "arrayIndexes", "=", "part", ".", "split", "(", "SPLIT_REG_EXP", ")", "tokens", ".", "push", "(", "arrayIndexes", "[", "0", "]", ")", "for", "(", "let", "j", "=", "1", ";", "j", "<", "arrayIndexes", ".", "length", ";", "j", "++", ")", "{", "if", "(", "arrayIndexes", "[", "j", "]", ".", "length", "===", "0", ")", "{", "continue", "}", "tokens", ".", "push", "(", "Number", "(", "arrayIndexes", "[", "j", "]", ")", ")", "}", "}", "return", "tokens", "}" ]
Parses the path. Splits it into keys for objects and indices for arrays. @private @returns {void}
[ "Parses", "the", "path", ".", "Splits", "it", "into", "keys", "for", "objects", "and", "indices", "for", "arrays", "." ]
247aea5e49a94f57f72fbac8e2f4dc0cdbbded18
https://github.com/deepstreamIO/deepstream.io/blob/247aea5e49a94f57f72fbac8e2f4dc0cdbbded18/src/record/json-path.js#L41-L66
6,408
deepstreamIO/deepstream.io
src/config/config-initialiser.js
handleSSLProperties
function handleSSLProperties (config) { const sslFiles = ['sslKey', 'sslCert', 'sslDHParams'] let key let resolvedFilePath let filePath for (let i = 0; i < sslFiles.length; i++) { key = sslFiles[i] filePath = config[key] if (!filePath) { continue } resolvedFilePath = fileUtils.lookupConfRequirePath(filePath) try { config[key] = fs.readFileSync(resolvedFilePath, 'utf8') } catch (e) { throw new Error(`The file path "${resolvedFilePath}" provided by "${key}" does not exist.`) } } }
javascript
function handleSSLProperties (config) { const sslFiles = ['sslKey', 'sslCert', 'sslDHParams'] let key let resolvedFilePath let filePath for (let i = 0; i < sslFiles.length; i++) { key = sslFiles[i] filePath = config[key] if (!filePath) { continue } resolvedFilePath = fileUtils.lookupConfRequirePath(filePath) try { config[key] = fs.readFileSync(resolvedFilePath, 'utf8') } catch (e) { throw new Error(`The file path "${resolvedFilePath}" provided by "${key}" does not exist.`) } } }
[ "function", "handleSSLProperties", "(", "config", ")", "{", "const", "sslFiles", "=", "[", "'sslKey'", ",", "'sslCert'", ",", "'sslDHParams'", "]", "let", "key", "let", "resolvedFilePath", "let", "filePath", "for", "(", "let", "i", "=", "0", ";", "i", "<", "sslFiles", ".", "length", ";", "i", "++", ")", "{", "key", "=", "sslFiles", "[", "i", "]", "filePath", "=", "config", "[", "key", "]", "if", "(", "!", "filePath", ")", "{", "continue", "}", "resolvedFilePath", "=", "fileUtils", ".", "lookupConfRequirePath", "(", "filePath", ")", "try", "{", "config", "[", "key", "]", "=", "fs", ".", "readFileSync", "(", "resolvedFilePath", ",", "'utf8'", ")", "}", "catch", "(", "e", ")", "{", "throw", "new", "Error", "(", "`", "${", "resolvedFilePath", "}", "${", "key", "}", "`", ")", "}", "}", "}" ]
Load the SSL files CLI arguments will be considered. @param {Object} config deepstream configuration object @private @returns {void}
[ "Load", "the", "SSL", "files", "CLI", "arguments", "will", "be", "considered", "." ]
247aea5e49a94f57f72fbac8e2f4dc0cdbbded18
https://github.com/deepstreamIO/deepstream.io/blob/247aea5e49a94f57f72fbac8e2f4dc0cdbbded18/src/config/config-initialiser.js#L68-L86
6,409
deepstreamIO/deepstream.io
src/config/config-initialiser.js
handleLogger
function handleLogger (config) { const configOptions = (config.logger || {}).options let Logger if (config.logger == null || config.logger.name === 'default') { Logger = DefaultLogger } else { Logger = resolvePluginClass(config.logger, 'logger') } if (configOptions instanceof Array) { // Note: This will not work on options without filename, and // is biased against for the winston logger let options for (let i = 0; i < configOptions.length; i++) { options = configOptions[i].options if (options && options.filename) { options.filename = fileUtils.lookupConfRequirePath(options.filename) } } } config.logger = new Logger(configOptions) if (!config.logger.info) { config.logger.debug = config.logger.log.bind(config.logger, C.LOG_LEVEL.DEBUG) config.logger.info = config.logger.log.bind(config.logger, C.LOG_LEVEL.INFO) config.logger.warn = config.logger.log.bind(config.logger, C.LOG_LEVEL.WARN) config.logger.error = config.logger.log.bind(config.logger, C.LOG_LEVEL.ERROR) } if (LOG_LEVEL_KEYS.indexOf(config.logLevel) !== -1) { // NOTE: config.logLevel has highest priority, compare to the level defined // in the nested logger object config.logLevel = C.LOG_LEVEL[config.logLevel] config.logger.setLogLevel(config.logLevel) } }
javascript
function handleLogger (config) { const configOptions = (config.logger || {}).options let Logger if (config.logger == null || config.logger.name === 'default') { Logger = DefaultLogger } else { Logger = resolvePluginClass(config.logger, 'logger') } if (configOptions instanceof Array) { // Note: This will not work on options without filename, and // is biased against for the winston logger let options for (let i = 0; i < configOptions.length; i++) { options = configOptions[i].options if (options && options.filename) { options.filename = fileUtils.lookupConfRequirePath(options.filename) } } } config.logger = new Logger(configOptions) if (!config.logger.info) { config.logger.debug = config.logger.log.bind(config.logger, C.LOG_LEVEL.DEBUG) config.logger.info = config.logger.log.bind(config.logger, C.LOG_LEVEL.INFO) config.logger.warn = config.logger.log.bind(config.logger, C.LOG_LEVEL.WARN) config.logger.error = config.logger.log.bind(config.logger, C.LOG_LEVEL.ERROR) } if (LOG_LEVEL_KEYS.indexOf(config.logLevel) !== -1) { // NOTE: config.logLevel has highest priority, compare to the level defined // in the nested logger object config.logLevel = C.LOG_LEVEL[config.logLevel] config.logger.setLogLevel(config.logLevel) } }
[ "function", "handleLogger", "(", "config", ")", "{", "const", "configOptions", "=", "(", "config", ".", "logger", "||", "{", "}", ")", ".", "options", "let", "Logger", "if", "(", "config", ".", "logger", "==", "null", "||", "config", ".", "logger", ".", "name", "===", "'default'", ")", "{", "Logger", "=", "DefaultLogger", "}", "else", "{", "Logger", "=", "resolvePluginClass", "(", "config", ".", "logger", ",", "'logger'", ")", "}", "if", "(", "configOptions", "instanceof", "Array", ")", "{", "// Note: This will not work on options without filename, and", "// is biased against for the winston logger", "let", "options", "for", "(", "let", "i", "=", "0", ";", "i", "<", "configOptions", ".", "length", ";", "i", "++", ")", "{", "options", "=", "configOptions", "[", "i", "]", ".", "options", "if", "(", "options", "&&", "options", ".", "filename", ")", "{", "options", ".", "filename", "=", "fileUtils", ".", "lookupConfRequirePath", "(", "options", ".", "filename", ")", "}", "}", "}", "config", ".", "logger", "=", "new", "Logger", "(", "configOptions", ")", "if", "(", "!", "config", ".", "logger", ".", "info", ")", "{", "config", ".", "logger", ".", "debug", "=", "config", ".", "logger", ".", "log", ".", "bind", "(", "config", ".", "logger", ",", "C", ".", "LOG_LEVEL", ".", "DEBUG", ")", "config", ".", "logger", ".", "info", "=", "config", ".", "logger", ".", "log", ".", "bind", "(", "config", ".", "logger", ",", "C", ".", "LOG_LEVEL", ".", "INFO", ")", "config", ".", "logger", ".", "warn", "=", "config", ".", "logger", ".", "log", ".", "bind", "(", "config", ".", "logger", ",", "C", ".", "LOG_LEVEL", ".", "WARN", ")", "config", ".", "logger", ".", "error", "=", "config", ".", "logger", ".", "log", ".", "bind", "(", "config", ".", "logger", ",", "C", ".", "LOG_LEVEL", ".", "ERROR", ")", "}", "if", "(", "LOG_LEVEL_KEYS", ".", "indexOf", "(", "config", ".", "logLevel", ")", "!==", "-", "1", ")", "{", "// NOTE: config.logLevel has highest priority, compare to the level defined", "// in the nested logger object", "config", ".", "logLevel", "=", "C", ".", "LOG_LEVEL", "[", "config", ".", "logLevel", "]", "config", ".", "logger", ".", "setLogLevel", "(", "config", ".", "logLevel", ")", "}", "}" ]
Initialize the logger and overwrite the root logLevel if it's set CLI arguments will be considered. @param {Object} config deepstream configuration object @private @returns {void}
[ "Initialize", "the", "logger", "and", "overwrite", "the", "root", "logLevel", "if", "it", "s", "set", "CLI", "arguments", "will", "be", "considered", "." ]
247aea5e49a94f57f72fbac8e2f4dc0cdbbded18
https://github.com/deepstreamIO/deepstream.io/blob/247aea5e49a94f57f72fbac8e2f4dc0cdbbded18/src/config/config-initialiser.js#L97-L131
6,410
deepstreamIO/deepstream.io
src/config/config-initialiser.js
resolvePluginClass
function resolvePluginClass (plugin, type) { // alias require to trick nexe from bundling it const req = require let requirePath let pluginConstructor if (plugin.path != null) { requirePath = fileUtils.lookupLibRequirePath(plugin.path) pluginConstructor = req(requirePath) } else if (plugin.name != null && type) { requirePath = `deepstream.io-${type}-${plugin.name}` requirePath = fileUtils.lookupLibRequirePath(requirePath) pluginConstructor = req(requirePath) } else if (plugin.name != null) { requirePath = fileUtils.lookupLibRequirePath(plugin.name) pluginConstructor = req(requirePath) } else { throw new Error(`Neither name nor path property found for ${type}`) } return pluginConstructor }
javascript
function resolvePluginClass (plugin, type) { // alias require to trick nexe from bundling it const req = require let requirePath let pluginConstructor if (plugin.path != null) { requirePath = fileUtils.lookupLibRequirePath(plugin.path) pluginConstructor = req(requirePath) } else if (plugin.name != null && type) { requirePath = `deepstream.io-${type}-${plugin.name}` requirePath = fileUtils.lookupLibRequirePath(requirePath) pluginConstructor = req(requirePath) } else if (plugin.name != null) { requirePath = fileUtils.lookupLibRequirePath(plugin.name) pluginConstructor = req(requirePath) } else { throw new Error(`Neither name nor path property found for ${type}`) } return pluginConstructor }
[ "function", "resolvePluginClass", "(", "plugin", ",", "type", ")", "{", "// alias require to trick nexe from bundling it", "const", "req", "=", "require", "let", "requirePath", "let", "pluginConstructor", "if", "(", "plugin", ".", "path", "!=", "null", ")", "{", "requirePath", "=", "fileUtils", ".", "lookupLibRequirePath", "(", "plugin", ".", "path", ")", "pluginConstructor", "=", "req", "(", "requirePath", ")", "}", "else", "if", "(", "plugin", ".", "name", "!=", "null", "&&", "type", ")", "{", "requirePath", "=", "`", "${", "type", "}", "${", "plugin", ".", "name", "}", "`", "requirePath", "=", "fileUtils", ".", "lookupLibRequirePath", "(", "requirePath", ")", "pluginConstructor", "=", "req", "(", "requirePath", ")", "}", "else", "if", "(", "plugin", ".", "name", "!=", "null", ")", "{", "requirePath", "=", "fileUtils", ".", "lookupLibRequirePath", "(", "plugin", ".", "name", ")", "pluginConstructor", "=", "req", "(", "requirePath", ")", "}", "else", "{", "throw", "new", "Error", "(", "`", "${", "type", "}", "`", ")", "}", "return", "pluginConstructor", "}" ]
Instantiate the given plugin, which either needs a path property or a name property which fits to the npm module name convention. Options will be passed to the constructor. CLI arguments will be considered. @param {Object} config deepstream configuration object @private @returns {Function} Instance return be the plugin constructor
[ "Instantiate", "the", "given", "plugin", "which", "either", "needs", "a", "path", "property", "or", "a", "name", "property", "which", "fits", "to", "the", "npm", "module", "name", "convention", ".", "Options", "will", "be", "passed", "to", "the", "constructor", "." ]
247aea5e49a94f57f72fbac8e2f4dc0cdbbded18
https://github.com/deepstreamIO/deepstream.io/blob/247aea5e49a94f57f72fbac8e2f4dc0cdbbded18/src/config/config-initialiser.js#L235-L254
6,411
deepstreamIO/deepstream.io
bin/installer.js
function (urlPath, outStream, callback) { needle.get(`https://github.com${urlPath}`, { follow_max: 5, headers: { 'User-Agent': 'nodejs-client' } }, (error, response) => { if (error) { return callback(error) } outStream.write(response.body) outStream.end() if (process.env.VERBOSE) { process.stdout.clearLine() process.stdout.cursorTo(0) process.stdout.write('Download complete' + '\n') } return callback() }) }
javascript
function (urlPath, outStream, callback) { needle.get(`https://github.com${urlPath}`, { follow_max: 5, headers: { 'User-Agent': 'nodejs-client' } }, (error, response) => { if (error) { return callback(error) } outStream.write(response.body) outStream.end() if (process.env.VERBOSE) { process.stdout.clearLine() process.stdout.cursorTo(0) process.stdout.write('Download complete' + '\n') } return callback() }) }
[ "function", "(", "urlPath", ",", "outStream", ",", "callback", ")", "{", "needle", ".", "get", "(", "`", "${", "urlPath", "}", "`", ",", "{", "follow_max", ":", "5", ",", "headers", ":", "{", "'User-Agent'", ":", "'nodejs-client'", "}", "}", ",", "(", "error", ",", "response", ")", "=>", "{", "if", "(", "error", ")", "{", "return", "callback", "(", "error", ")", "}", "outStream", ".", "write", "(", "response", ".", "body", ")", "outStream", ".", "end", "(", ")", "if", "(", "process", ".", "env", ".", "VERBOSE", ")", "{", "process", ".", "stdout", ".", "clearLine", "(", ")", "process", ".", "stdout", ".", "cursorTo", "(", "0", ")", "process", ".", "stdout", ".", "write", "(", "'Download complete'", "+", "'\\n'", ")", "}", "return", "callback", "(", ")", "}", ")", "}" ]
Downloads an archive usually zip or tar.gz from a URL which comes from the GitHub release API. @param {String} urlPath URL where to download the archive @param {Stream} writeable output stream to save the archive @param {Function} callback Callback (err) @return {void}
[ "Downloads", "an", "archive", "usually", "zip", "or", "tar", ".", "gz", "from", "a", "URL", "which", "comes", "from", "the", "GitHub", "release", "API", "." ]
247aea5e49a94f57f72fbac8e2f4dc0cdbbded18
https://github.com/deepstreamIO/deepstream.io/blob/247aea5e49a94f57f72fbac8e2f4dc0cdbbded18/bin/installer.js#L91-L108
6,412
deepstreamIO/deepstream.io
bin/installer.js
function (directory) { try { const content = fs.readFileSync(path.join(directory, CONFIG_EXAMPLE_FILE), 'utf8') if (process.env.VERBOSE) { console.log('You need to configure the connector in your deepstream configuration file') } if (!process.env.QUIET) { console.log(`Example configuration:\n${colors.grey(content)}`) } } catch (err) { if (!process.env.QUIET) { console.log('Example configuration not found') } } }
javascript
function (directory) { try { const content = fs.readFileSync(path.join(directory, CONFIG_EXAMPLE_FILE), 'utf8') if (process.env.VERBOSE) { console.log('You need to configure the connector in your deepstream configuration file') } if (!process.env.QUIET) { console.log(`Example configuration:\n${colors.grey(content)}`) } } catch (err) { if (!process.env.QUIET) { console.log('Example configuration not found') } } }
[ "function", "(", "directory", ")", "{", "try", "{", "const", "content", "=", "fs", ".", "readFileSync", "(", "path", ".", "join", "(", "directory", ",", "CONFIG_EXAMPLE_FILE", ")", ",", "'utf8'", ")", "if", "(", "process", ".", "env", ".", "VERBOSE", ")", "{", "console", ".", "log", "(", "'You need to configure the connector in your deepstream configuration file'", ")", "}", "if", "(", "!", "process", ".", "env", ".", "QUIET", ")", "{", "console", ".", "log", "(", "`", "\\n", "${", "colors", ".", "grey", "(", "content", ")", "}", "`", ")", "}", "}", "catch", "(", "err", ")", "{", "if", "(", "!", "process", ".", "env", ".", "QUIET", ")", "{", "console", ".", "log", "(", "'Example configuration not found'", ")", "}", "}", "}" ]
Prints out the config snippet of a extract connector to the stdout. Output is indented and grey colored. @param {String} directory where to lookup for CONFIG_EXAMPLE_FILE @return {void}
[ "Prints", "out", "the", "config", "snippet", "of", "a", "extract", "connector", "to", "the", "stdout", ".", "Output", "is", "indented", "and", "grey", "colored", "." ]
247aea5e49a94f57f72fbac8e2f4dc0cdbbded18
https://github.com/deepstreamIO/deepstream.io/blob/247aea5e49a94f57f72fbac8e2f4dc0cdbbded18/bin/installer.js#L193-L207
6,413
deepstreamIO/deepstream.io
src/config/file-utils.js
resolvePrefixAndFile
function resolvePrefixAndFile (nonAbsoluteFilePath, prefix) { // prefix is not absolute if (path.parse(prefix).root === '') { return path.resolve(process.cwd(), prefix, nonAbsoluteFilePath) } // prefix is absolute return path.resolve(prefix, nonAbsoluteFilePath) }
javascript
function resolvePrefixAndFile (nonAbsoluteFilePath, prefix) { // prefix is not absolute if (path.parse(prefix).root === '') { return path.resolve(process.cwd(), prefix, nonAbsoluteFilePath) } // prefix is absolute return path.resolve(prefix, nonAbsoluteFilePath) }
[ "function", "resolvePrefixAndFile", "(", "nonAbsoluteFilePath", ",", "prefix", ")", "{", "// prefix is not absolute", "if", "(", "path", ".", "parse", "(", "prefix", ")", ".", "root", "===", "''", ")", "{", "return", "path", ".", "resolve", "(", "process", ".", "cwd", "(", ")", ",", "prefix", ",", "nonAbsoluteFilePath", ")", "}", "// prefix is absolute", "return", "path", ".", "resolve", "(", "prefix", ",", "nonAbsoluteFilePath", ")", "}" ]
Append the prefix to the current working directory, or use it as an absolute path @param {String} nonAbsoluteFilePath @param {String} prefix @private @returns {String} resolvedPath
[ "Append", "the", "prefix", "to", "the", "current", "working", "directory", "or", "use", "it", "as", "an", "absolute", "path" ]
247aea5e49a94f57f72fbac8e2f4dc0cdbbded18
https://github.com/deepstreamIO/deepstream.io/blob/247aea5e49a94f57f72fbac8e2f4dc0cdbbded18/src/config/file-utils.js#L100-L108
6,414
patternfly/patternfly-react
scripts/incrementalBuild.js
getInvalidPackages
async function getInvalidPackages() { const packages = (await new Project(__dirname).getPackages()) .filter(p => p.scripts.build) // Only packages that have a build target .filter(p => isPf3 ? p.location.indexOf('patternfly-3') !== -1 || commonPackages.indexOf(p.name) !== -1 : true) // Based off argv .filter(p => isPf4 ? p.location.indexOf('patternfly-4') !== -1 || commonPackages.indexOf(p.name) !== -1 : true) // Based off argv for (let p of packages) { const watchDir = getDir(p.name); p.hash = (await hashElement(`${p.location}/${watchDir}`)).hash; p.valid = cache && cache[p.name] === p.hash; if (p.valid) { console.info('Skipping', p.name, '(already built).'); } } return packages.filter(p => !p.valid); }
javascript
async function getInvalidPackages() { const packages = (await new Project(__dirname).getPackages()) .filter(p => p.scripts.build) // Only packages that have a build target .filter(p => isPf3 ? p.location.indexOf('patternfly-3') !== -1 || commonPackages.indexOf(p.name) !== -1 : true) // Based off argv .filter(p => isPf4 ? p.location.indexOf('patternfly-4') !== -1 || commonPackages.indexOf(p.name) !== -1 : true) // Based off argv for (let p of packages) { const watchDir = getDir(p.name); p.hash = (await hashElement(`${p.location}/${watchDir}`)).hash; p.valid = cache && cache[p.name] === p.hash; if (p.valid) { console.info('Skipping', p.name, '(already built).'); } } return packages.filter(p => !p.valid); }
[ "async", "function", "getInvalidPackages", "(", ")", "{", "const", "packages", "=", "(", "await", "new", "Project", "(", "__dirname", ")", ".", "getPackages", "(", ")", ")", ".", "filter", "(", "p", "=>", "p", ".", "scripts", ".", "build", ")", "// Only packages that have a build target", ".", "filter", "(", "p", "=>", "isPf3", "?", "p", ".", "location", ".", "indexOf", "(", "'patternfly-3'", ")", "!==", "-", "1", "||", "commonPackages", ".", "indexOf", "(", "p", ".", "name", ")", "!==", "-", "1", ":", "true", ")", "// Based off argv", ".", "filter", "(", "p", "=>", "isPf4", "?", "p", ".", "location", ".", "indexOf", "(", "'patternfly-4'", ")", "!==", "-", "1", "||", "commonPackages", ".", "indexOf", "(", "p", ".", "name", ")", "!==", "-", "1", ":", "true", ")", "// Based off argv", "for", "(", "let", "p", "of", "packages", ")", "{", "const", "watchDir", "=", "getDir", "(", "p", ".", "name", ")", ";", "p", ".", "hash", "=", "(", "await", "hashElement", "(", "`", "${", "p", ".", "location", "}", "${", "watchDir", "}", "`", ")", ")", ".", "hash", ";", "p", ".", "valid", "=", "cache", "&&", "cache", "[", "p", ".", "name", "]", "===", "p", ".", "hash", ";", "if", "(", "p", ".", "valid", ")", "{", "console", ".", "info", "(", "'Skipping'", ",", "p", ".", "name", ",", "'(already built).'", ")", ";", "}", "}", "return", "packages", ".", "filter", "(", "p", "=>", "!", "p", ".", "valid", ")", ";", "}" ]
These are packages we need to rebuild
[ "These", "are", "packages", "we", "need", "to", "rebuild" ]
82f8002e30b41888d4f22daffe170f0f733ec591
https://github.com/patternfly/patternfly-react/blob/82f8002e30b41888d4f22daffe170f0f733ec591/scripts/incrementalBuild.js#L31-L51
6,415
dimsemenov/Magnific-Popup
src/js/core.js
function() { if(!mfp.isOpen) return; _mfpTrigger(BEFORE_CLOSE_EVENT); mfp.isOpen = false; // for CSS3 animation if(mfp.st.removalDelay && !mfp.isLowIE && mfp.supportsTransition ) { mfp._addClassToMFP(REMOVING_CLASS); setTimeout(function() { mfp._close(); }, mfp.st.removalDelay); } else { mfp._close(); } }
javascript
function() { if(!mfp.isOpen) return; _mfpTrigger(BEFORE_CLOSE_EVENT); mfp.isOpen = false; // for CSS3 animation if(mfp.st.removalDelay && !mfp.isLowIE && mfp.supportsTransition ) { mfp._addClassToMFP(REMOVING_CLASS); setTimeout(function() { mfp._close(); }, mfp.st.removalDelay); } else { mfp._close(); } }
[ "function", "(", ")", "{", "if", "(", "!", "mfp", ".", "isOpen", ")", "return", ";", "_mfpTrigger", "(", "BEFORE_CLOSE_EVENT", ")", ";", "mfp", ".", "isOpen", "=", "false", ";", "// for CSS3 animation", "if", "(", "mfp", ".", "st", ".", "removalDelay", "&&", "!", "mfp", ".", "isLowIE", "&&", "mfp", ".", "supportsTransition", ")", "{", "mfp", ".", "_addClassToMFP", "(", "REMOVING_CLASS", ")", ";", "setTimeout", "(", "function", "(", ")", "{", "mfp", ".", "_close", "(", ")", ";", "}", ",", "mfp", ".", "st", ".", "removalDelay", ")", ";", "}", "else", "{", "mfp", ".", "_close", "(", ")", ";", "}", "}" ]
Closes the popup
[ "Closes", "the", "popup" ]
c8f6b8549ebff2306c5f1179c9d112308185fe2c
https://github.com/dimsemenov/Magnific-Popup/blob/c8f6b8549ebff2306c5f1179c9d112308185fe2c/src/js/core.js#L370-L384
6,416
dimsemenov/Magnific-Popup
src/js/core.js
function() { var item = mfp.items[mfp.index]; // Detach and perform modifications mfp.contentContainer.detach(); if(mfp.content) mfp.content.detach(); if(!item.parsed) { item = mfp.parseEl( mfp.index ); } var type = item.type; _mfpTrigger('BeforeChange', [mfp.currItem ? mfp.currItem.type : '', type]); // BeforeChange event works like so: // _mfpOn('BeforeChange', function(e, prevType, newType) { }); mfp.currItem = item; if(!mfp.currTemplate[type]) { var markup = mfp.st[type] ? mfp.st[type].markup : false; // allows to modify markup _mfpTrigger('FirstMarkupParse', markup); if(markup) { mfp.currTemplate[type] = $(markup); } else { // if there is no markup found we just define that template is parsed mfp.currTemplate[type] = true; } } if(_prevContentType && _prevContentType !== item.type) { mfp.container.removeClass('mfp-'+_prevContentType+'-holder'); } var newContent = mfp['get' + type.charAt(0).toUpperCase() + type.slice(1)](item, mfp.currTemplate[type]); mfp.appendContent(newContent, type); item.preloaded = true; _mfpTrigger(CHANGE_EVENT, item); _prevContentType = item.type; // Append container back after its content changed mfp.container.prepend(mfp.contentContainer); _mfpTrigger('AfterChange'); }
javascript
function() { var item = mfp.items[mfp.index]; // Detach and perform modifications mfp.contentContainer.detach(); if(mfp.content) mfp.content.detach(); if(!item.parsed) { item = mfp.parseEl( mfp.index ); } var type = item.type; _mfpTrigger('BeforeChange', [mfp.currItem ? mfp.currItem.type : '', type]); // BeforeChange event works like so: // _mfpOn('BeforeChange', function(e, prevType, newType) { }); mfp.currItem = item; if(!mfp.currTemplate[type]) { var markup = mfp.st[type] ? mfp.st[type].markup : false; // allows to modify markup _mfpTrigger('FirstMarkupParse', markup); if(markup) { mfp.currTemplate[type] = $(markup); } else { // if there is no markup found we just define that template is parsed mfp.currTemplate[type] = true; } } if(_prevContentType && _prevContentType !== item.type) { mfp.container.removeClass('mfp-'+_prevContentType+'-holder'); } var newContent = mfp['get' + type.charAt(0).toUpperCase() + type.slice(1)](item, mfp.currTemplate[type]); mfp.appendContent(newContent, type); item.preloaded = true; _mfpTrigger(CHANGE_EVENT, item); _prevContentType = item.type; // Append container back after its content changed mfp.container.prepend(mfp.contentContainer); _mfpTrigger('AfterChange'); }
[ "function", "(", ")", "{", "var", "item", "=", "mfp", ".", "items", "[", "mfp", ".", "index", "]", ";", "// Detach and perform modifications", "mfp", ".", "contentContainer", ".", "detach", "(", ")", ";", "if", "(", "mfp", ".", "content", ")", "mfp", ".", "content", ".", "detach", "(", ")", ";", "if", "(", "!", "item", ".", "parsed", ")", "{", "item", "=", "mfp", ".", "parseEl", "(", "mfp", ".", "index", ")", ";", "}", "var", "type", "=", "item", ".", "type", ";", "_mfpTrigger", "(", "'BeforeChange'", ",", "[", "mfp", ".", "currItem", "?", "mfp", ".", "currItem", ".", "type", ":", "''", ",", "type", "]", ")", ";", "// BeforeChange event works like so:", "// _mfpOn('BeforeChange', function(e, prevType, newType) { });", "mfp", ".", "currItem", "=", "item", ";", "if", "(", "!", "mfp", ".", "currTemplate", "[", "type", "]", ")", "{", "var", "markup", "=", "mfp", ".", "st", "[", "type", "]", "?", "mfp", ".", "st", "[", "type", "]", ".", "markup", ":", "false", ";", "// allows to modify markup", "_mfpTrigger", "(", "'FirstMarkupParse'", ",", "markup", ")", ";", "if", "(", "markup", ")", "{", "mfp", ".", "currTemplate", "[", "type", "]", "=", "$", "(", "markup", ")", ";", "}", "else", "{", "// if there is no markup found we just define that template is parsed", "mfp", ".", "currTemplate", "[", "type", "]", "=", "true", ";", "}", "}", "if", "(", "_prevContentType", "&&", "_prevContentType", "!==", "item", ".", "type", ")", "{", "mfp", ".", "container", ".", "removeClass", "(", "'mfp-'", "+", "_prevContentType", "+", "'-holder'", ")", ";", "}", "var", "newContent", "=", "mfp", "[", "'get'", "+", "type", ".", "charAt", "(", "0", ")", ".", "toUpperCase", "(", ")", "+", "type", ".", "slice", "(", "1", ")", "]", "(", "item", ",", "mfp", ".", "currTemplate", "[", "type", "]", ")", ";", "mfp", ".", "appendContent", "(", "newContent", ",", "type", ")", ";", "item", ".", "preloaded", "=", "true", ";", "_mfpTrigger", "(", "CHANGE_EVENT", ",", "item", ")", ";", "_prevContentType", "=", "item", ".", "type", ";", "// Append container back after its content changed", "mfp", ".", "container", ".", "prepend", "(", "mfp", ".", "contentContainer", ")", ";", "_mfpTrigger", "(", "'AfterChange'", ")", ";", "}" ]
Set content of popup based on current index
[ "Set", "content", "of", "popup", "based", "on", "current", "index" ]
c8f6b8549ebff2306c5f1179c9d112308185fe2c
https://github.com/dimsemenov/Magnific-Popup/blob/c8f6b8549ebff2306c5f1179c9d112308185fe2c/src/js/core.js#L464-L515
6,417
dimsemenov/Magnific-Popup
src/js/core.js
function(newContent, type) { mfp.content = newContent; if(newContent) { if(mfp.st.showCloseBtn && mfp.st.closeBtnInside && mfp.currTemplate[type] === true) { // if there is no markup, we just append close button element inside if(!mfp.content.find('.mfp-close').length) { mfp.content.append(_getCloseBtn()); } } else { mfp.content = newContent; } } else { mfp.content = ''; } _mfpTrigger(BEFORE_APPEND_EVENT); mfp.container.addClass('mfp-'+type+'-holder'); mfp.contentContainer.append(mfp.content); }
javascript
function(newContent, type) { mfp.content = newContent; if(newContent) { if(mfp.st.showCloseBtn && mfp.st.closeBtnInside && mfp.currTemplate[type] === true) { // if there is no markup, we just append close button element inside if(!mfp.content.find('.mfp-close').length) { mfp.content.append(_getCloseBtn()); } } else { mfp.content = newContent; } } else { mfp.content = ''; } _mfpTrigger(BEFORE_APPEND_EVENT); mfp.container.addClass('mfp-'+type+'-holder'); mfp.contentContainer.append(mfp.content); }
[ "function", "(", "newContent", ",", "type", ")", "{", "mfp", ".", "content", "=", "newContent", ";", "if", "(", "newContent", ")", "{", "if", "(", "mfp", ".", "st", ".", "showCloseBtn", "&&", "mfp", ".", "st", ".", "closeBtnInside", "&&", "mfp", ".", "currTemplate", "[", "type", "]", "===", "true", ")", "{", "// if there is no markup, we just append close button element inside", "if", "(", "!", "mfp", ".", "content", ".", "find", "(", "'.mfp-close'", ")", ".", "length", ")", "{", "mfp", ".", "content", ".", "append", "(", "_getCloseBtn", "(", ")", ")", ";", "}", "}", "else", "{", "mfp", ".", "content", "=", "newContent", ";", "}", "}", "else", "{", "mfp", ".", "content", "=", "''", ";", "}", "_mfpTrigger", "(", "BEFORE_APPEND_EVENT", ")", ";", "mfp", ".", "container", ".", "addClass", "(", "'mfp-'", "+", "type", "+", "'-holder'", ")", ";", "mfp", ".", "contentContainer", ".", "append", "(", "mfp", ".", "content", ")", ";", "}" ]
Set HTML content of popup
[ "Set", "HTML", "content", "of", "popup" ]
c8f6b8549ebff2306c5f1179c9d112308185fe2c
https://github.com/dimsemenov/Magnific-Popup/blob/c8f6b8549ebff2306c5f1179c9d112308185fe2c/src/js/core.js#L521-L542
6,418
dimsemenov/Magnific-Popup
src/js/core.js
function(index) { var item = mfp.items[index], type; if(item.tagName) { item = { el: $(item) }; } else { type = item.type; item = { data: item, src: item.src }; } if(item.el) { var types = mfp.types; // check for 'mfp-TYPE' class for(var i = 0; i < types.length; i++) { if( item.el.hasClass('mfp-'+types[i]) ) { type = types[i]; break; } } item.src = item.el.attr('data-mfp-src'); if(!item.src) { item.src = item.el.attr('href'); } } item.type = type || mfp.st.type || 'inline'; item.index = index; item.parsed = true; mfp.items[index] = item; _mfpTrigger('ElementParse', item); return mfp.items[index]; }
javascript
function(index) { var item = mfp.items[index], type; if(item.tagName) { item = { el: $(item) }; } else { type = item.type; item = { data: item, src: item.src }; } if(item.el) { var types = mfp.types; // check for 'mfp-TYPE' class for(var i = 0; i < types.length; i++) { if( item.el.hasClass('mfp-'+types[i]) ) { type = types[i]; break; } } item.src = item.el.attr('data-mfp-src'); if(!item.src) { item.src = item.el.attr('href'); } } item.type = type || mfp.st.type || 'inline'; item.index = index; item.parsed = true; mfp.items[index] = item; _mfpTrigger('ElementParse', item); return mfp.items[index]; }
[ "function", "(", "index", ")", "{", "var", "item", "=", "mfp", ".", "items", "[", "index", "]", ",", "type", ";", "if", "(", "item", ".", "tagName", ")", "{", "item", "=", "{", "el", ":", "$", "(", "item", ")", "}", ";", "}", "else", "{", "type", "=", "item", ".", "type", ";", "item", "=", "{", "data", ":", "item", ",", "src", ":", "item", ".", "src", "}", ";", "}", "if", "(", "item", ".", "el", ")", "{", "var", "types", "=", "mfp", ".", "types", ";", "// check for 'mfp-TYPE' class", "for", "(", "var", "i", "=", "0", ";", "i", "<", "types", ".", "length", ";", "i", "++", ")", "{", "if", "(", "item", ".", "el", ".", "hasClass", "(", "'mfp-'", "+", "types", "[", "i", "]", ")", ")", "{", "type", "=", "types", "[", "i", "]", ";", "break", ";", "}", "}", "item", ".", "src", "=", "item", ".", "el", ".", "attr", "(", "'data-mfp-src'", ")", ";", "if", "(", "!", "item", ".", "src", ")", "{", "item", ".", "src", "=", "item", ".", "el", ".", "attr", "(", "'href'", ")", ";", "}", "}", "item", ".", "type", "=", "type", "||", "mfp", ".", "st", ".", "type", "||", "'inline'", ";", "item", ".", "index", "=", "index", ";", "item", ".", "parsed", "=", "true", ";", "mfp", ".", "items", "[", "index", "]", "=", "item", ";", "_mfpTrigger", "(", "'ElementParse'", ",", "item", ")", ";", "return", "mfp", ".", "items", "[", "index", "]", ";", "}" ]
Creates Magnific Popup data object based on given data @param {int} index Index of item to parse
[ "Creates", "Magnific", "Popup", "data", "object", "based", "on", "given", "data" ]
c8f6b8549ebff2306c5f1179c9d112308185fe2c
https://github.com/dimsemenov/Magnific-Popup/blob/c8f6b8549ebff2306c5f1179c9d112308185fe2c/src/js/core.js#L549-L584
6,419
dimsemenov/Magnific-Popup
src/js/core.js
function(el, options) { var eHandler = function(e) { e.mfpEl = this; mfp._openClick(e, el, options); }; if(!options) { options = {}; } var eName = 'click.magnificPopup'; options.mainEl = el; if(options.items) { options.isObj = true; el.off(eName).on(eName, eHandler); } else { options.isObj = false; if(options.delegate) { el.off(eName).on(eName, options.delegate , eHandler); } else { options.items = el; el.off(eName).on(eName, eHandler); } } }
javascript
function(el, options) { var eHandler = function(e) { e.mfpEl = this; mfp._openClick(e, el, options); }; if(!options) { options = {}; } var eName = 'click.magnificPopup'; options.mainEl = el; if(options.items) { options.isObj = true; el.off(eName).on(eName, eHandler); } else { options.isObj = false; if(options.delegate) { el.off(eName).on(eName, options.delegate , eHandler); } else { options.items = el; el.off(eName).on(eName, eHandler); } } }
[ "function", "(", "el", ",", "options", ")", "{", "var", "eHandler", "=", "function", "(", "e", ")", "{", "e", ".", "mfpEl", "=", "this", ";", "mfp", ".", "_openClick", "(", "e", ",", "el", ",", "options", ")", ";", "}", ";", "if", "(", "!", "options", ")", "{", "options", "=", "{", "}", ";", "}", "var", "eName", "=", "'click.magnificPopup'", ";", "options", ".", "mainEl", "=", "el", ";", "if", "(", "options", ".", "items", ")", "{", "options", ".", "isObj", "=", "true", ";", "el", ".", "off", "(", "eName", ")", ".", "on", "(", "eName", ",", "eHandler", ")", ";", "}", "else", "{", "options", ".", "isObj", "=", "false", ";", "if", "(", "options", ".", "delegate", ")", "{", "el", ".", "off", "(", "eName", ")", ".", "on", "(", "eName", ",", "options", ".", "delegate", ",", "eHandler", ")", ";", "}", "else", "{", "options", ".", "items", "=", "el", ";", "el", ".", "off", "(", "eName", ")", ".", "on", "(", "eName", ",", "eHandler", ")", ";", "}", "}", "}" ]
Initializes single popup or a group of popups
[ "Initializes", "single", "popup", "or", "a", "group", "of", "popups" ]
c8f6b8549ebff2306c5f1179c9d112308185fe2c
https://github.com/dimsemenov/Magnific-Popup/blob/c8f6b8549ebff2306c5f1179c9d112308185fe2c/src/js/core.js#L590-L615
6,420
dimsemenov/Magnific-Popup
src/js/core.js
function(status, text) { if(mfp.preloader) { if(_prevStatus !== status) { mfp.container.removeClass('mfp-s-'+_prevStatus); } if(!text && status === 'loading') { text = mfp.st.tLoading; } var data = { status: status, text: text }; // allows to modify status _mfpTrigger('UpdateStatus', data); status = data.status; text = data.text; mfp.preloader.html(text); mfp.preloader.find('a').on('click', function(e) { e.stopImmediatePropagation(); }); mfp.container.addClass('mfp-s-'+status); _prevStatus = status; } }
javascript
function(status, text) { if(mfp.preloader) { if(_prevStatus !== status) { mfp.container.removeClass('mfp-s-'+_prevStatus); } if(!text && status === 'loading') { text = mfp.st.tLoading; } var data = { status: status, text: text }; // allows to modify status _mfpTrigger('UpdateStatus', data); status = data.status; text = data.text; mfp.preloader.html(text); mfp.preloader.find('a').on('click', function(e) { e.stopImmediatePropagation(); }); mfp.container.addClass('mfp-s-'+status); _prevStatus = status; } }
[ "function", "(", "status", ",", "text", ")", "{", "if", "(", "mfp", ".", "preloader", ")", "{", "if", "(", "_prevStatus", "!==", "status", ")", "{", "mfp", ".", "container", ".", "removeClass", "(", "'mfp-s-'", "+", "_prevStatus", ")", ";", "}", "if", "(", "!", "text", "&&", "status", "===", "'loading'", ")", "{", "text", "=", "mfp", ".", "st", ".", "tLoading", ";", "}", "var", "data", "=", "{", "status", ":", "status", ",", "text", ":", "text", "}", ";", "// allows to modify status", "_mfpTrigger", "(", "'UpdateStatus'", ",", "data", ")", ";", "status", "=", "data", ".", "status", ";", "text", "=", "data", ".", "text", ";", "mfp", ".", "preloader", ".", "html", "(", "text", ")", ";", "mfp", ".", "preloader", ".", "find", "(", "'a'", ")", ".", "on", "(", "'click'", ",", "function", "(", "e", ")", "{", "e", ".", "stopImmediatePropagation", "(", ")", ";", "}", ")", ";", "mfp", ".", "container", ".", "addClass", "(", "'mfp-s-'", "+", "status", ")", ";", "_prevStatus", "=", "status", ";", "}", "}" ]
Updates text on preloader
[ "Updates", "text", "on", "preloader" ]
c8f6b8549ebff2306c5f1179c9d112308185fe2c
https://github.com/dimsemenov/Magnific-Popup/blob/c8f6b8549ebff2306c5f1179c9d112308185fe2c/src/js/core.js#L658-L688
6,421
dimsemenov/Magnific-Popup
website/third-party-libs/zepto.js
deserializeValue
function deserializeValue(value) { var num try { return value ? value == "true" || ( value == "false" ? false : value == "null" ? null : !isNaN(num = Number(value)) ? num : /^[\[\{]/.test(value) ? $.parseJSON(value) : value ) : value } catch(e) { return value } }
javascript
function deserializeValue(value) { var num try { return value ? value == "true" || ( value == "false" ? false : value == "null" ? null : !isNaN(num = Number(value)) ? num : /^[\[\{]/.test(value) ? $.parseJSON(value) : value ) : value } catch(e) { return value } }
[ "function", "deserializeValue", "(", "value", ")", "{", "var", "num", "try", "{", "return", "value", "?", "value", "==", "\"true\"", "||", "(", "value", "==", "\"false\"", "?", "false", ":", "value", "==", "\"null\"", "?", "null", ":", "!", "isNaN", "(", "num", "=", "Number", "(", "value", ")", ")", "?", "num", ":", "/", "^[\\[\\{]", "/", ".", "test", "(", "value", ")", "?", "$", ".", "parseJSON", "(", "value", ")", ":", "value", ")", ":", "value", "}", "catch", "(", "e", ")", "{", "return", "value", "}", "}" ]
"true" => true "false" => false "null" => null "42" => 42 "42.5" => 42.5 JSON => parse if valid String => self
[ "true", "=", ">", "true", "false", "=", ">", "false", "null", "=", ">", "null", "42", "=", ">", "42", "42", ".", "5", "=", ">", "42", ".", "5", "JSON", "=", ">", "parse", "if", "valid", "String", "=", ">", "self" ]
c8f6b8549ebff2306c5f1179c9d112308185fe2c
https://github.com/dimsemenov/Magnific-Popup/blob/c8f6b8549ebff2306c5f1179c9d112308185fe2c/website/third-party-libs/zepto.js#L289-L303
6,422
dimsemenov/Magnific-Popup
website/third-party-libs/zepto.js
fix
function fix(event) { if (!('defaultPrevented' in event)) { event.defaultPrevented = false var prevent = event.preventDefault event.preventDefault = function() { this.defaultPrevented = true prevent.call(this) } } }
javascript
function fix(event) { if (!('defaultPrevented' in event)) { event.defaultPrevented = false var prevent = event.preventDefault event.preventDefault = function() { this.defaultPrevented = true prevent.call(this) } } }
[ "function", "fix", "(", "event", ")", "{", "if", "(", "!", "(", "'defaultPrevented'", "in", "event", ")", ")", "{", "event", ".", "defaultPrevented", "=", "false", "var", "prevent", "=", "event", ".", "preventDefault", "event", ".", "preventDefault", "=", "function", "(", ")", "{", "this", ".", "defaultPrevented", "=", "true", "prevent", ".", "call", "(", "this", ")", "}", "}", "}" ]
emulates the 'defaultPrevented' property for browsers that have none
[ "emulates", "the", "defaultPrevented", "property", "for", "browsers", "that", "have", "none" ]
c8f6b8549ebff2306c5f1179c9d112308185fe2c
https://github.com/dimsemenov/Magnific-Popup/blob/c8f6b8549ebff2306c5f1179c9d112308185fe2c/website/third-party-libs/zepto.js#L1012-L1021
6,423
dimsemenov/Magnific-Popup
src/js/image.js
function(item) { var counter = 0, img = item.img[0], mfpSetInterval = function(delay) { if(_imgInterval) { clearInterval(_imgInterval); } // decelerating interval that checks for size of an image _imgInterval = setInterval(function() { if(img.naturalWidth > 0) { mfp._onImageHasSize(item); return; } if(counter > 200) { clearInterval(_imgInterval); } counter++; if(counter === 3) { mfpSetInterval(10); } else if(counter === 40) { mfpSetInterval(50); } else if(counter === 100) { mfpSetInterval(500); } }, delay); }; mfpSetInterval(1); }
javascript
function(item) { var counter = 0, img = item.img[0], mfpSetInterval = function(delay) { if(_imgInterval) { clearInterval(_imgInterval); } // decelerating interval that checks for size of an image _imgInterval = setInterval(function() { if(img.naturalWidth > 0) { mfp._onImageHasSize(item); return; } if(counter > 200) { clearInterval(_imgInterval); } counter++; if(counter === 3) { mfpSetInterval(10); } else if(counter === 40) { mfpSetInterval(50); } else if(counter === 100) { mfpSetInterval(500); } }, delay); }; mfpSetInterval(1); }
[ "function", "(", "item", ")", "{", "var", "counter", "=", "0", ",", "img", "=", "item", ".", "img", "[", "0", "]", ",", "mfpSetInterval", "=", "function", "(", "delay", ")", "{", "if", "(", "_imgInterval", ")", "{", "clearInterval", "(", "_imgInterval", ")", ";", "}", "// decelerating interval that checks for size of an image", "_imgInterval", "=", "setInterval", "(", "function", "(", ")", "{", "if", "(", "img", ".", "naturalWidth", ">", "0", ")", "{", "mfp", ".", "_onImageHasSize", "(", "item", ")", ";", "return", ";", "}", "if", "(", "counter", ">", "200", ")", "{", "clearInterval", "(", "_imgInterval", ")", ";", "}", "counter", "++", ";", "if", "(", "counter", "===", "3", ")", "{", "mfpSetInterval", "(", "10", ")", ";", "}", "else", "if", "(", "counter", "===", "40", ")", "{", "mfpSetInterval", "(", "50", ")", ";", "}", "else", "if", "(", "counter", "===", "100", ")", "{", "mfpSetInterval", "(", "500", ")", ";", "}", "}", ",", "delay", ")", ";", "}", ";", "mfpSetInterval", "(", "1", ")", ";", "}" ]
Function that loops until the image has size to display elements that rely on it asap
[ "Function", "that", "loops", "until", "the", "image", "has", "size", "to", "display", "elements", "that", "rely", "on", "it", "asap" ]
c8f6b8549ebff2306c5f1179c9d112308185fe2c
https://github.com/dimsemenov/Magnific-Popup/blob/c8f6b8549ebff2306c5f1179c9d112308185fe2c/src/js/image.js#L103-L135
6,424
inorganik/countUp.js
demo.js
createCountUp
function createCountUp() { establishOptionsFromInputs(); demo = new CountUp('myTargetElement', endVal, options); if (!demo.error) { errorSection.style.display = 'none'; if (input('useOnComplete').checked) { demo.start(methodToCallOnComplete); } else { demo.start(); } updateCodeVisualizer(); } else { errorSection.style.display = 'block'; document.getElementById('error').innerHTML = demo.error; console.error(demo.error); } }
javascript
function createCountUp() { establishOptionsFromInputs(); demo = new CountUp('myTargetElement', endVal, options); if (!demo.error) { errorSection.style.display = 'none'; if (input('useOnComplete').checked) { demo.start(methodToCallOnComplete); } else { demo.start(); } updateCodeVisualizer(); } else { errorSection.style.display = 'block'; document.getElementById('error').innerHTML = demo.error; console.error(demo.error); } }
[ "function", "createCountUp", "(", ")", "{", "establishOptionsFromInputs", "(", ")", ";", "demo", "=", "new", "CountUp", "(", "'myTargetElement'", ",", "endVal", ",", "options", ")", ";", "if", "(", "!", "demo", ".", "error", ")", "{", "errorSection", ".", "style", ".", "display", "=", "'none'", ";", "if", "(", "input", "(", "'useOnComplete'", ")", ".", "checked", ")", "{", "demo", ".", "start", "(", "methodToCallOnComplete", ")", ";", "}", "else", "{", "demo", ".", "start", "(", ")", ";", "}", "updateCodeVisualizer", "(", ")", ";", "}", "else", "{", "errorSection", ".", "style", ".", "display", "=", "'block'", ";", "document", ".", "getElementById", "(", "'error'", ")", ".", "innerHTML", "=", "demo", ".", "error", ";", "console", ".", "error", "(", "demo", ".", "error", ")", ";", "}", "}" ]
COUNTUP AND CODE VISUALIZER
[ "COUNTUP", "AND", "CODE", "VISUALIZER" ]
29ba37c1f4f02a00ef19c9abbdc58d1b610f7d38
https://github.com/inorganik/countUp.js/blob/29ba37c1f4f02a00ef19c9abbdc58d1b610f7d38/demo.js#L108-L126
6,425
mongodb/node-mongodb-native
lib/change_stream.js
function(self) { if (self.resumeToken) { self.options.resumeAfter = self.resumeToken; } var changeStreamCursor = buildChangeStreamAggregationCommand(self); /** * Fired for each new matching change in the specified namespace. Attaching a `change` * event listener to a Change Stream will switch the stream into flowing mode. Data will * then be passed as soon as it is available. * * @event ChangeStream#change * @type {object} */ if (self.listenerCount('change') > 0) { changeStreamCursor.on('data', function(change) { processNewChange({ changeStream: self, change, eventEmitter: true }); }); } /** * Change stream close event * * @event ChangeStream#close * @type {null} */ changeStreamCursor.on('close', function() { self.emit('close'); }); /** * Change stream end event * * @event ChangeStream#end * @type {null} */ changeStreamCursor.on('end', function() { self.emit('end'); }); /** * Fired when the stream encounters an error. * * @event ChangeStream#error * @type {Error} */ changeStreamCursor.on('error', function(error) { processNewChange({ changeStream: self, error, eventEmitter: true }); }); if (self.pipeDestinations) { const cursorStream = changeStreamCursor.stream(self.streamOptions); for (let pipeDestination in self.pipeDestinations) { cursorStream.pipe(pipeDestination); } } return changeStreamCursor; }
javascript
function(self) { if (self.resumeToken) { self.options.resumeAfter = self.resumeToken; } var changeStreamCursor = buildChangeStreamAggregationCommand(self); /** * Fired for each new matching change in the specified namespace. Attaching a `change` * event listener to a Change Stream will switch the stream into flowing mode. Data will * then be passed as soon as it is available. * * @event ChangeStream#change * @type {object} */ if (self.listenerCount('change') > 0) { changeStreamCursor.on('data', function(change) { processNewChange({ changeStream: self, change, eventEmitter: true }); }); } /** * Change stream close event * * @event ChangeStream#close * @type {null} */ changeStreamCursor.on('close', function() { self.emit('close'); }); /** * Change stream end event * * @event ChangeStream#end * @type {null} */ changeStreamCursor.on('end', function() { self.emit('end'); }); /** * Fired when the stream encounters an error. * * @event ChangeStream#error * @type {Error} */ changeStreamCursor.on('error', function(error) { processNewChange({ changeStream: self, error, eventEmitter: true }); }); if (self.pipeDestinations) { const cursorStream = changeStreamCursor.stream(self.streamOptions); for (let pipeDestination in self.pipeDestinations) { cursorStream.pipe(pipeDestination); } } return changeStreamCursor; }
[ "function", "(", "self", ")", "{", "if", "(", "self", ".", "resumeToken", ")", "{", "self", ".", "options", ".", "resumeAfter", "=", "self", ".", "resumeToken", ";", "}", "var", "changeStreamCursor", "=", "buildChangeStreamAggregationCommand", "(", "self", ")", ";", "/**\n * Fired for each new matching change in the specified namespace. Attaching a `change`\n * event listener to a Change Stream will switch the stream into flowing mode. Data will\n * then be passed as soon as it is available.\n *\n * @event ChangeStream#change\n * @type {object}\n */", "if", "(", "self", ".", "listenerCount", "(", "'change'", ")", ">", "0", ")", "{", "changeStreamCursor", ".", "on", "(", "'data'", ",", "function", "(", "change", ")", "{", "processNewChange", "(", "{", "changeStream", ":", "self", ",", "change", ",", "eventEmitter", ":", "true", "}", ")", ";", "}", ")", ";", "}", "/**\n * Change stream close event\n *\n * @event ChangeStream#close\n * @type {null}\n */", "changeStreamCursor", ".", "on", "(", "'close'", ",", "function", "(", ")", "{", "self", ".", "emit", "(", "'close'", ")", ";", "}", ")", ";", "/**\n * Change stream end event\n *\n * @event ChangeStream#end\n * @type {null}\n */", "changeStreamCursor", ".", "on", "(", "'end'", ",", "function", "(", ")", "{", "self", ".", "emit", "(", "'end'", ")", ";", "}", ")", ";", "/**\n * Fired when the stream encounters an error.\n *\n * @event ChangeStream#error\n * @type {Error}\n */", "changeStreamCursor", ".", "on", "(", "'error'", ",", "function", "(", "error", ")", "{", "processNewChange", "(", "{", "changeStream", ":", "self", ",", "error", ",", "eventEmitter", ":", "true", "}", ")", ";", "}", ")", ";", "if", "(", "self", ".", "pipeDestinations", ")", "{", "const", "cursorStream", "=", "changeStreamCursor", ".", "stream", "(", "self", ".", "streamOptions", ")", ";", "for", "(", "let", "pipeDestination", "in", "self", ".", "pipeDestinations", ")", "{", "cursorStream", ".", "pipe", "(", "pipeDestination", ")", ";", "}", "}", "return", "changeStreamCursor", ";", "}" ]
Create a new change stream cursor based on self's configuration
[ "Create", "a", "new", "change", "stream", "cursor", "based", "on", "self", "s", "configuration" ]
0afbbccf1bd7d437610c33cbd5523f01bc6bc6e5
https://github.com/mongodb/node-mongodb-native/blob/0afbbccf1bd7d437610c33cbd5523f01bc6bc6e5/lib/change_stream.js#L224-L283
6,426
mongodb/node-mongodb-native
lib/gridfs-stream/index.js
GridFSBucket
function GridFSBucket(db, options) { Emitter.apply(this); this.setMaxListeners(0); if (options && typeof options === 'object') { options = shallowClone(options); var keys = Object.keys(DEFAULT_GRIDFS_BUCKET_OPTIONS); for (var i = 0; i < keys.length; ++i) { if (!options[keys[i]]) { options[keys[i]] = DEFAULT_GRIDFS_BUCKET_OPTIONS[keys[i]]; } } } else { options = DEFAULT_GRIDFS_BUCKET_OPTIONS; } this.s = { db: db, options: options, _chunksCollection: db.collection(options.bucketName + '.chunks'), _filesCollection: db.collection(options.bucketName + '.files'), checkedIndexes: false, calledOpenUploadStream: false, promiseLibrary: db.s.promiseLibrary || Promise }; }
javascript
function GridFSBucket(db, options) { Emitter.apply(this); this.setMaxListeners(0); if (options && typeof options === 'object') { options = shallowClone(options); var keys = Object.keys(DEFAULT_GRIDFS_BUCKET_OPTIONS); for (var i = 0; i < keys.length; ++i) { if (!options[keys[i]]) { options[keys[i]] = DEFAULT_GRIDFS_BUCKET_OPTIONS[keys[i]]; } } } else { options = DEFAULT_GRIDFS_BUCKET_OPTIONS; } this.s = { db: db, options: options, _chunksCollection: db.collection(options.bucketName + '.chunks'), _filesCollection: db.collection(options.bucketName + '.files'), checkedIndexes: false, calledOpenUploadStream: false, promiseLibrary: db.s.promiseLibrary || Promise }; }
[ "function", "GridFSBucket", "(", "db", ",", "options", ")", "{", "Emitter", ".", "apply", "(", "this", ")", ";", "this", ".", "setMaxListeners", "(", "0", ")", ";", "if", "(", "options", "&&", "typeof", "options", "===", "'object'", ")", "{", "options", "=", "shallowClone", "(", "options", ")", ";", "var", "keys", "=", "Object", ".", "keys", "(", "DEFAULT_GRIDFS_BUCKET_OPTIONS", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "keys", ".", "length", ";", "++", "i", ")", "{", "if", "(", "!", "options", "[", "keys", "[", "i", "]", "]", ")", "{", "options", "[", "keys", "[", "i", "]", "]", "=", "DEFAULT_GRIDFS_BUCKET_OPTIONS", "[", "keys", "[", "i", "]", "]", ";", "}", "}", "}", "else", "{", "options", "=", "DEFAULT_GRIDFS_BUCKET_OPTIONS", ";", "}", "this", ".", "s", "=", "{", "db", ":", "db", ",", "options", ":", "options", ",", "_chunksCollection", ":", "db", ".", "collection", "(", "options", ".", "bucketName", "+", "'.chunks'", ")", ",", "_filesCollection", ":", "db", ".", "collection", "(", "options", ".", "bucketName", "+", "'.files'", ")", ",", "checkedIndexes", ":", "false", ",", "calledOpenUploadStream", ":", "false", ",", "promiseLibrary", ":", "db", ".", "s", ".", "promiseLibrary", "||", "Promise", "}", ";", "}" ]
Constructor for a streaming GridFS interface @class @param {Db} db A db handle @param {object} [options] Optional settings. @param {string} [options.bucketName="fs"] The 'files' and 'chunks' collections will be prefixed with the bucket name followed by a dot. @param {number} [options.chunkSizeBytes=255 * 1024] Number of bytes stored in each chunk. Defaults to 255KB @param {object} [options.writeConcern] Optional write concern to be passed to write operations, for instance `{ w: 1 }` @param {object} [options.readPreference] Optional read preference to be passed to read operations @fires GridFSBucketWriteStream#index @return {GridFSBucket}
[ "Constructor", "for", "a", "streaming", "GridFS", "interface" ]
0afbbccf1bd7d437610c33cbd5523f01bc6bc6e5
https://github.com/mongodb/node-mongodb-native/blob/0afbbccf1bd7d437610c33cbd5523f01bc6bc6e5/lib/gridfs-stream/index.js#L31-L56
6,427
mongodb/node-mongodb-native
lib/operations/db_ops.js
collections
function collections(db, options, callback) { let Collection = loadCollection(); options = Object.assign({}, options, { nameOnly: true }); // Let's get the collection names db.listCollections({}, options).toArray((err, documents) => { if (err != null) return handleCallback(callback, err, null); // Filter collections removing any illegal ones documents = documents.filter(doc => { return doc.name.indexOf('$') === -1; }); // Return the collection objects handleCallback( callback, null, documents.map(d => { return new Collection( db, db.s.topology, db.s.databaseName, d.name, db.s.pkFactory, db.s.options ); }) ); }); }
javascript
function collections(db, options, callback) { let Collection = loadCollection(); options = Object.assign({}, options, { nameOnly: true }); // Let's get the collection names db.listCollections({}, options).toArray((err, documents) => { if (err != null) return handleCallback(callback, err, null); // Filter collections removing any illegal ones documents = documents.filter(doc => { return doc.name.indexOf('$') === -1; }); // Return the collection objects handleCallback( callback, null, documents.map(d => { return new Collection( db, db.s.topology, db.s.databaseName, d.name, db.s.pkFactory, db.s.options ); }) ); }); }
[ "function", "collections", "(", "db", ",", "options", ",", "callback", ")", "{", "let", "Collection", "=", "loadCollection", "(", ")", ";", "options", "=", "Object", ".", "assign", "(", "{", "}", ",", "options", ",", "{", "nameOnly", ":", "true", "}", ")", ";", "// Let's get the collection names", "db", ".", "listCollections", "(", "{", "}", ",", "options", ")", ".", "toArray", "(", "(", "err", ",", "documents", ")", "=>", "{", "if", "(", "err", "!=", "null", ")", "return", "handleCallback", "(", "callback", ",", "err", ",", "null", ")", ";", "// Filter collections removing any illegal ones", "documents", "=", "documents", ".", "filter", "(", "doc", "=>", "{", "return", "doc", ".", "name", ".", "indexOf", "(", "'$'", ")", "===", "-", "1", ";", "}", ")", ";", "// Return the collection objects", "handleCallback", "(", "callback", ",", "null", ",", "documents", ".", "map", "(", "d", "=>", "{", "return", "new", "Collection", "(", "db", ",", "db", ".", "s", ".", "topology", ",", "db", ".", "s", ".", "databaseName", ",", "d", ".", "name", ",", "db", ".", "s", ".", "pkFactory", ",", "db", ".", "s", ".", "options", ")", ";", "}", ")", ")", ";", "}", ")", ";", "}" ]
Fetch all collections for the current db. @method @param {Db} db The Db instance on which to fetch collections. @param {object} [options] Optional settings. See Db.prototype.collections for a list of options. @param {Db~collectionsResultCallback} [callback] The results callback
[ "Fetch", "all", "collections", "for", "the", "current", "db", "." ]
0afbbccf1bd7d437610c33cbd5523f01bc6bc6e5
https://github.com/mongodb/node-mongodb-native/blob/0afbbccf1bd7d437610c33cbd5523f01bc6bc6e5/lib/operations/db_ops.js#L149-L177
6,428
mongodb/node-mongodb-native
lib/operations/db_ops.js
createIndex
function createIndex(db, name, fieldOrSpec, options, callback) { // Get the write concern options let finalOptions = Object.assign({}, { readPreference: ReadPreference.PRIMARY }, options); finalOptions = applyWriteConcern(finalOptions, { db }, options); // Ensure we have a callback if (finalOptions.writeConcern && typeof callback !== 'function') { throw MongoError.create({ message: 'Cannot use a writeConcern without a provided callback', driver: true }); } // Did the user destroy the topology if (db.serverConfig && db.serverConfig.isDestroyed()) return callback(new MongoError('topology was destroyed')); // Attempt to run using createIndexes command createIndexUsingCreateIndexes(db, name, fieldOrSpec, finalOptions, (err, result) => { if (err == null) return handleCallback(callback, err, result); /** * The following errors mean that the server recognized `createIndex` as a command so we don't need to fallback to an insert: * 67 = 'CannotCreateIndex' (malformed index options) * 85 = 'IndexOptionsConflict' (index already exists with different options) * 86 = 'IndexKeySpecsConflict' (index already exists with the same name) * 11000 = 'DuplicateKey' (couldn't build unique index because of dupes) * 11600 = 'InterruptedAtShutdown' (interrupted at shutdown) * 197 = 'InvalidIndexSpecificationOption' (`_id` with `background: true`) */ if ( err.code === 67 || err.code === 11000 || err.code === 85 || err.code === 86 || err.code === 11600 || err.code === 197 ) { return handleCallback(callback, err, result); } // Create command const doc = createCreateIndexCommand(db, name, fieldOrSpec, options); // Set no key checking finalOptions.checkKeys = false; // Insert document db.s.topology.insert( `${db.s.databaseName}.${CONSTANTS.SYSTEM_INDEX_COLLECTION}`, doc, finalOptions, (err, result) => { if (callback == null) return; if (err) return handleCallback(callback, err); if (result == null) return handleCallback(callback, null, null); if (result.result.writeErrors) return handleCallback(callback, MongoError.create(result.result.writeErrors[0]), null); handleCallback(callback, null, doc.name); } ); }); }
javascript
function createIndex(db, name, fieldOrSpec, options, callback) { // Get the write concern options let finalOptions = Object.assign({}, { readPreference: ReadPreference.PRIMARY }, options); finalOptions = applyWriteConcern(finalOptions, { db }, options); // Ensure we have a callback if (finalOptions.writeConcern && typeof callback !== 'function') { throw MongoError.create({ message: 'Cannot use a writeConcern without a provided callback', driver: true }); } // Did the user destroy the topology if (db.serverConfig && db.serverConfig.isDestroyed()) return callback(new MongoError('topology was destroyed')); // Attempt to run using createIndexes command createIndexUsingCreateIndexes(db, name, fieldOrSpec, finalOptions, (err, result) => { if (err == null) return handleCallback(callback, err, result); /** * The following errors mean that the server recognized `createIndex` as a command so we don't need to fallback to an insert: * 67 = 'CannotCreateIndex' (malformed index options) * 85 = 'IndexOptionsConflict' (index already exists with different options) * 86 = 'IndexKeySpecsConflict' (index already exists with the same name) * 11000 = 'DuplicateKey' (couldn't build unique index because of dupes) * 11600 = 'InterruptedAtShutdown' (interrupted at shutdown) * 197 = 'InvalidIndexSpecificationOption' (`_id` with `background: true`) */ if ( err.code === 67 || err.code === 11000 || err.code === 85 || err.code === 86 || err.code === 11600 || err.code === 197 ) { return handleCallback(callback, err, result); } // Create command const doc = createCreateIndexCommand(db, name, fieldOrSpec, options); // Set no key checking finalOptions.checkKeys = false; // Insert document db.s.topology.insert( `${db.s.databaseName}.${CONSTANTS.SYSTEM_INDEX_COLLECTION}`, doc, finalOptions, (err, result) => { if (callback == null) return; if (err) return handleCallback(callback, err); if (result == null) return handleCallback(callback, null, null); if (result.result.writeErrors) return handleCallback(callback, MongoError.create(result.result.writeErrors[0]), null); handleCallback(callback, null, doc.name); } ); }); }
[ "function", "createIndex", "(", "db", ",", "name", ",", "fieldOrSpec", ",", "options", ",", "callback", ")", "{", "// Get the write concern options", "let", "finalOptions", "=", "Object", ".", "assign", "(", "{", "}", ",", "{", "readPreference", ":", "ReadPreference", ".", "PRIMARY", "}", ",", "options", ")", ";", "finalOptions", "=", "applyWriteConcern", "(", "finalOptions", ",", "{", "db", "}", ",", "options", ")", ";", "// Ensure we have a callback", "if", "(", "finalOptions", ".", "writeConcern", "&&", "typeof", "callback", "!==", "'function'", ")", "{", "throw", "MongoError", ".", "create", "(", "{", "message", ":", "'Cannot use a writeConcern without a provided callback'", ",", "driver", ":", "true", "}", ")", ";", "}", "// Did the user destroy the topology", "if", "(", "db", ".", "serverConfig", "&&", "db", ".", "serverConfig", ".", "isDestroyed", "(", ")", ")", "return", "callback", "(", "new", "MongoError", "(", "'topology was destroyed'", ")", ")", ";", "// Attempt to run using createIndexes command", "createIndexUsingCreateIndexes", "(", "db", ",", "name", ",", "fieldOrSpec", ",", "finalOptions", ",", "(", "err", ",", "result", ")", "=>", "{", "if", "(", "err", "==", "null", ")", "return", "handleCallback", "(", "callback", ",", "err", ",", "result", ")", ";", "/**\n * The following errors mean that the server recognized `createIndex` as a command so we don't need to fallback to an insert:\n * 67 = 'CannotCreateIndex' (malformed index options)\n * 85 = 'IndexOptionsConflict' (index already exists with different options)\n * 86 = 'IndexKeySpecsConflict' (index already exists with the same name)\n * 11000 = 'DuplicateKey' (couldn't build unique index because of dupes)\n * 11600 = 'InterruptedAtShutdown' (interrupted at shutdown)\n * 197 = 'InvalidIndexSpecificationOption' (`_id` with `background: true`)\n */", "if", "(", "err", ".", "code", "===", "67", "||", "err", ".", "code", "===", "11000", "||", "err", ".", "code", "===", "85", "||", "err", ".", "code", "===", "86", "||", "err", ".", "code", "===", "11600", "||", "err", ".", "code", "===", "197", ")", "{", "return", "handleCallback", "(", "callback", ",", "err", ",", "result", ")", ";", "}", "// Create command", "const", "doc", "=", "createCreateIndexCommand", "(", "db", ",", "name", ",", "fieldOrSpec", ",", "options", ")", ";", "// Set no key checking", "finalOptions", ".", "checkKeys", "=", "false", ";", "// Insert document", "db", ".", "s", ".", "topology", ".", "insert", "(", "`", "${", "db", ".", "s", ".", "databaseName", "}", "${", "CONSTANTS", ".", "SYSTEM_INDEX_COLLECTION", "}", "`", ",", "doc", ",", "finalOptions", ",", "(", "err", ",", "result", ")", "=>", "{", "if", "(", "callback", "==", "null", ")", "return", ";", "if", "(", "err", ")", "return", "handleCallback", "(", "callback", ",", "err", ")", ";", "if", "(", "result", "==", "null", ")", "return", "handleCallback", "(", "callback", ",", "null", ",", "null", ")", ";", "if", "(", "result", ".", "result", ".", "writeErrors", ")", "return", "handleCallback", "(", "callback", ",", "MongoError", ".", "create", "(", "result", ".", "result", ".", "writeErrors", "[", "0", "]", ")", ",", "null", ")", ";", "handleCallback", "(", "callback", ",", "null", ",", "doc", ".", "name", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Creates an index on the db and collection. @method @param {Db} db The Db instance on which to create an index. @param {string} name Name of the collection to create the index on. @param {(string|object)} fieldOrSpec Defines the index. @param {object} [options] Optional settings. See Db.prototype.createIndex for a list of options. @param {Db~resultCallback} [callback] The command result callback
[ "Creates", "an", "index", "on", "the", "db", "and", "collection", "." ]
0afbbccf1bd7d437610c33cbd5523f01bc6bc6e5
https://github.com/mongodb/node-mongodb-native/blob/0afbbccf1bd7d437610c33cbd5523f01bc6bc6e5/lib/operations/db_ops.js#L274-L334
6,429
mongodb/node-mongodb-native
lib/operations/db_ops.js
createListener
function createListener(db, e, object) { function listener(err) { if (object.listeners(e).length > 0) { object.emit(e, err, db); // Emit on all associated db's if available for (let i = 0; i < db.s.children.length; i++) { db.s.children[i].emit(e, err, db.s.children[i]); } } } return listener; }
javascript
function createListener(db, e, object) { function listener(err) { if (object.listeners(e).length > 0) { object.emit(e, err, db); // Emit on all associated db's if available for (let i = 0; i < db.s.children.length; i++) { db.s.children[i].emit(e, err, db.s.children[i]); } } } return listener; }
[ "function", "createListener", "(", "db", ",", "e", ",", "object", ")", "{", "function", "listener", "(", "err", ")", "{", "if", "(", "object", ".", "listeners", "(", "e", ")", ".", "length", ">", "0", ")", "{", "object", ".", "emit", "(", "e", ",", "err", ",", "db", ")", ";", "// Emit on all associated db's if available", "for", "(", "let", "i", "=", "0", ";", "i", "<", "db", ".", "s", ".", "children", ".", "length", ";", "i", "++", ")", "{", "db", ".", "s", ".", "children", "[", "i", "]", ".", "emit", "(", "e", ",", "err", ",", "db", ".", "s", ".", "children", "[", "i", "]", ")", ";", "}", "}", "}", "return", "listener", ";", "}" ]
Add listeners to topology
[ "Add", "listeners", "to", "topology" ]
0afbbccf1bd7d437610c33cbd5523f01bc6bc6e5
https://github.com/mongodb/node-mongodb-native/blob/0afbbccf1bd7d437610c33cbd5523f01bc6bc6e5/lib/operations/db_ops.js#L337-L349
6,430
mongodb/node-mongodb-native
lib/operations/db_ops.js
dropCollection
function dropCollection(db, name, options, callback) { executeCommand(db, name, options, (err, result) => { // Did the user destroy the topology if (db.serverConfig && db.serverConfig.isDestroyed()) { return callback(new MongoError('topology was destroyed')); } if (err) return handleCallback(callback, err); if (result.ok) return handleCallback(callback, null, true); handleCallback(callback, null, false); }); }
javascript
function dropCollection(db, name, options, callback) { executeCommand(db, name, options, (err, result) => { // Did the user destroy the topology if (db.serverConfig && db.serverConfig.isDestroyed()) { return callback(new MongoError('topology was destroyed')); } if (err) return handleCallback(callback, err); if (result.ok) return handleCallback(callback, null, true); handleCallback(callback, null, false); }); }
[ "function", "dropCollection", "(", "db", ",", "name", ",", "options", ",", "callback", ")", "{", "executeCommand", "(", "db", ",", "name", ",", "options", ",", "(", "err", ",", "result", ")", "=>", "{", "// Did the user destroy the topology", "if", "(", "db", ".", "serverConfig", "&&", "db", ".", "serverConfig", ".", "isDestroyed", "(", ")", ")", "{", "return", "callback", "(", "new", "MongoError", "(", "'topology was destroyed'", ")", ")", ";", "}", "if", "(", "err", ")", "return", "handleCallback", "(", "callback", ",", "err", ")", ";", "if", "(", "result", ".", "ok", ")", "return", "handleCallback", "(", "callback", ",", "null", ",", "true", ")", ";", "handleCallback", "(", "callback", ",", "null", ",", "false", ")", ";", "}", ")", ";", "}" ]
Drop a collection from the database, removing it permanently. New accesses will create a new collection. @method @param {Db} db The Db instance on which to drop the collection. @param {string} name Name of collection to drop @param {Object} [options] Optional settings. See Db.prototype.dropCollection for a list of options. @param {Db~resultCallback} [callback] The results callback
[ "Drop", "a", "collection", "from", "the", "database", "removing", "it", "permanently", ".", "New", "accesses", "will", "create", "a", "new", "collection", "." ]
0afbbccf1bd7d437610c33cbd5523f01bc6bc6e5
https://github.com/mongodb/node-mongodb-native/blob/0afbbccf1bd7d437610c33cbd5523f01bc6bc6e5/lib/operations/db_ops.js#L360-L371
6,431
mongodb/node-mongodb-native
lib/operations/db_ops.js
dropDatabase
function dropDatabase(db, cmd, options, callback) { executeCommand(db, cmd, options, (err, result) => { // Did the user destroy the topology if (db.serverConfig && db.serverConfig.isDestroyed()) { return callback(new MongoError('topology was destroyed')); } if (callback == null) return; if (err) return handleCallback(callback, err, null); handleCallback(callback, null, result.ok ? true : false); }); }
javascript
function dropDatabase(db, cmd, options, callback) { executeCommand(db, cmd, options, (err, result) => { // Did the user destroy the topology if (db.serverConfig && db.serverConfig.isDestroyed()) { return callback(new MongoError('topology was destroyed')); } if (callback == null) return; if (err) return handleCallback(callback, err, null); handleCallback(callback, null, result.ok ? true : false); }); }
[ "function", "dropDatabase", "(", "db", ",", "cmd", ",", "options", ",", "callback", ")", "{", "executeCommand", "(", "db", ",", "cmd", ",", "options", ",", "(", "err", ",", "result", ")", "=>", "{", "// Did the user destroy the topology", "if", "(", "db", ".", "serverConfig", "&&", "db", ".", "serverConfig", ".", "isDestroyed", "(", ")", ")", "{", "return", "callback", "(", "new", "MongoError", "(", "'topology was destroyed'", ")", ")", ";", "}", "if", "(", "callback", "==", "null", ")", "return", ";", "if", "(", "err", ")", "return", "handleCallback", "(", "callback", ",", "err", ",", "null", ")", ";", "handleCallback", "(", "callback", ",", "null", ",", "result", ".", "ok", "?", "true", ":", "false", ")", ";", "}", ")", ";", "}" ]
Drop a database, removing it permanently from the server. @method @param {Db} db The Db instance to drop. @param {Object} cmd The command document. @param {Object} [options] Optional settings. See Db.prototype.dropDatabase for a list of options. @param {Db~resultCallback} [callback] The results callback
[ "Drop", "a", "database", "removing", "it", "permanently", "from", "the", "server", "." ]
0afbbccf1bd7d437610c33cbd5523f01bc6bc6e5
https://github.com/mongodb/node-mongodb-native/blob/0afbbccf1bd7d437610c33cbd5523f01bc6bc6e5/lib/operations/db_ops.js#L382-L393
6,432
mongodb/node-mongodb-native
lib/operations/db_ops.js
ensureIndex
function ensureIndex(db, name, fieldOrSpec, options, callback) { // Get the write concern options const finalOptions = applyWriteConcern({}, { db }, options); // Create command const selector = createCreateIndexCommand(db, name, fieldOrSpec, options); const index_name = selector.name; // Did the user destroy the topology if (db.serverConfig && db.serverConfig.isDestroyed()) return callback(new MongoError('topology was destroyed')); // Merge primary readPreference finalOptions.readPreference = ReadPreference.PRIMARY; // Check if the index already exists indexInformation(db, name, finalOptions, (err, indexInformation) => { if (err != null && err.code !== 26) return handleCallback(callback, err, null); // If the index does not exist, create it if (indexInformation == null || !indexInformation[index_name]) { createIndex(db, name, fieldOrSpec, options, callback); } else { if (typeof callback === 'function') return handleCallback(callback, null, index_name); } }); }
javascript
function ensureIndex(db, name, fieldOrSpec, options, callback) { // Get the write concern options const finalOptions = applyWriteConcern({}, { db }, options); // Create command const selector = createCreateIndexCommand(db, name, fieldOrSpec, options); const index_name = selector.name; // Did the user destroy the topology if (db.serverConfig && db.serverConfig.isDestroyed()) return callback(new MongoError('topology was destroyed')); // Merge primary readPreference finalOptions.readPreference = ReadPreference.PRIMARY; // Check if the index already exists indexInformation(db, name, finalOptions, (err, indexInformation) => { if (err != null && err.code !== 26) return handleCallback(callback, err, null); // If the index does not exist, create it if (indexInformation == null || !indexInformation[index_name]) { createIndex(db, name, fieldOrSpec, options, callback); } else { if (typeof callback === 'function') return handleCallback(callback, null, index_name); } }); }
[ "function", "ensureIndex", "(", "db", ",", "name", ",", "fieldOrSpec", ",", "options", ",", "callback", ")", "{", "// Get the write concern options", "const", "finalOptions", "=", "applyWriteConcern", "(", "{", "}", ",", "{", "db", "}", ",", "options", ")", ";", "// Create command", "const", "selector", "=", "createCreateIndexCommand", "(", "db", ",", "name", ",", "fieldOrSpec", ",", "options", ")", ";", "const", "index_name", "=", "selector", ".", "name", ";", "// Did the user destroy the topology", "if", "(", "db", ".", "serverConfig", "&&", "db", ".", "serverConfig", ".", "isDestroyed", "(", ")", ")", "return", "callback", "(", "new", "MongoError", "(", "'topology was destroyed'", ")", ")", ";", "// Merge primary readPreference", "finalOptions", ".", "readPreference", "=", "ReadPreference", ".", "PRIMARY", ";", "// Check if the index already exists", "indexInformation", "(", "db", ",", "name", ",", "finalOptions", ",", "(", "err", ",", "indexInformation", ")", "=>", "{", "if", "(", "err", "!=", "null", "&&", "err", ".", "code", "!==", "26", ")", "return", "handleCallback", "(", "callback", ",", "err", ",", "null", ")", ";", "// If the index does not exist, create it", "if", "(", "indexInformation", "==", "null", "||", "!", "indexInformation", "[", "index_name", "]", ")", "{", "createIndex", "(", "db", ",", "name", ",", "fieldOrSpec", ",", "options", ",", "callback", ")", ";", "}", "else", "{", "if", "(", "typeof", "callback", "===", "'function'", ")", "return", "handleCallback", "(", "callback", ",", "null", ",", "index_name", ")", ";", "}", "}", ")", ";", "}" ]
Ensures that an index exists. If it does not, creates it. @method @param {Db} db The Db instance on which to ensure the index. @param {string} name The index name @param {(string|object)} fieldOrSpec Defines the index. @param {object} [options] Optional settings. See Db.prototype.ensureIndex for a list of options. @param {Db~resultCallback} [callback] The command result callback
[ "Ensures", "that", "an", "index", "exists", ".", "If", "it", "does", "not", "creates", "it", "." ]
0afbbccf1bd7d437610c33cbd5523f01bc6bc6e5
https://github.com/mongodb/node-mongodb-native/blob/0afbbccf1bd7d437610c33cbd5523f01bc6bc6e5/lib/operations/db_ops.js#L405-L429
6,433
mongodb/node-mongodb-native
lib/operations/db_ops.js
evaluate
function evaluate(db, code, parameters, options, callback) { let finalCode = code; let finalParameters = []; // Did the user destroy the topology if (db.serverConfig && db.serverConfig.isDestroyed()) return callback(new MongoError('topology was destroyed')); // If not a code object translate to one if (!(finalCode && finalCode._bsontype === 'Code')) finalCode = new Code(finalCode); // Ensure the parameters are correct if (parameters != null && !Array.isArray(parameters) && typeof parameters !== 'function') { finalParameters = [parameters]; } else if (parameters != null && Array.isArray(parameters) && typeof parameters !== 'function') { finalParameters = parameters; } // Create execution selector let cmd = { $eval: finalCode, args: finalParameters }; // Check if the nolock parameter is passed in if (options['nolock']) { cmd['nolock'] = options['nolock']; } // Set primary read preference options.readPreference = new ReadPreference(ReadPreference.PRIMARY); // Execute the command executeCommand(db, cmd, options, (err, result) => { if (err) return handleCallback(callback, err, null); if (result && result.ok === 1) return handleCallback(callback, null, result.retval); if (result) return handleCallback( callback, MongoError.create({ message: `eval failed: ${result.errmsg}`, driver: true }), null ); handleCallback(callback, err, result); }); }
javascript
function evaluate(db, code, parameters, options, callback) { let finalCode = code; let finalParameters = []; // Did the user destroy the topology if (db.serverConfig && db.serverConfig.isDestroyed()) return callback(new MongoError('topology was destroyed')); // If not a code object translate to one if (!(finalCode && finalCode._bsontype === 'Code')) finalCode = new Code(finalCode); // Ensure the parameters are correct if (parameters != null && !Array.isArray(parameters) && typeof parameters !== 'function') { finalParameters = [parameters]; } else if (parameters != null && Array.isArray(parameters) && typeof parameters !== 'function') { finalParameters = parameters; } // Create execution selector let cmd = { $eval: finalCode, args: finalParameters }; // Check if the nolock parameter is passed in if (options['nolock']) { cmd['nolock'] = options['nolock']; } // Set primary read preference options.readPreference = new ReadPreference(ReadPreference.PRIMARY); // Execute the command executeCommand(db, cmd, options, (err, result) => { if (err) return handleCallback(callback, err, null); if (result && result.ok === 1) return handleCallback(callback, null, result.retval); if (result) return handleCallback( callback, MongoError.create({ message: `eval failed: ${result.errmsg}`, driver: true }), null ); handleCallback(callback, err, result); }); }
[ "function", "evaluate", "(", "db", ",", "code", ",", "parameters", ",", "options", ",", "callback", ")", "{", "let", "finalCode", "=", "code", ";", "let", "finalParameters", "=", "[", "]", ";", "// Did the user destroy the topology", "if", "(", "db", ".", "serverConfig", "&&", "db", ".", "serverConfig", ".", "isDestroyed", "(", ")", ")", "return", "callback", "(", "new", "MongoError", "(", "'topology was destroyed'", ")", ")", ";", "// If not a code object translate to one", "if", "(", "!", "(", "finalCode", "&&", "finalCode", ".", "_bsontype", "===", "'Code'", ")", ")", "finalCode", "=", "new", "Code", "(", "finalCode", ")", ";", "// Ensure the parameters are correct", "if", "(", "parameters", "!=", "null", "&&", "!", "Array", ".", "isArray", "(", "parameters", ")", "&&", "typeof", "parameters", "!==", "'function'", ")", "{", "finalParameters", "=", "[", "parameters", "]", ";", "}", "else", "if", "(", "parameters", "!=", "null", "&&", "Array", ".", "isArray", "(", "parameters", ")", "&&", "typeof", "parameters", "!==", "'function'", ")", "{", "finalParameters", "=", "parameters", ";", "}", "// Create execution selector", "let", "cmd", "=", "{", "$eval", ":", "finalCode", ",", "args", ":", "finalParameters", "}", ";", "// Check if the nolock parameter is passed in", "if", "(", "options", "[", "'nolock'", "]", ")", "{", "cmd", "[", "'nolock'", "]", "=", "options", "[", "'nolock'", "]", ";", "}", "// Set primary read preference", "options", ".", "readPreference", "=", "new", "ReadPreference", "(", "ReadPreference", ".", "PRIMARY", ")", ";", "// Execute the command", "executeCommand", "(", "db", ",", "cmd", ",", "options", ",", "(", "err", ",", "result", ")", "=>", "{", "if", "(", "err", ")", "return", "handleCallback", "(", "callback", ",", "err", ",", "null", ")", ";", "if", "(", "result", "&&", "result", ".", "ok", "===", "1", ")", "return", "handleCallback", "(", "callback", ",", "null", ",", "result", ".", "retval", ")", ";", "if", "(", "result", ")", "return", "handleCallback", "(", "callback", ",", "MongoError", ".", "create", "(", "{", "message", ":", "`", "${", "result", ".", "errmsg", "}", "`", ",", "driver", ":", "true", "}", ")", ",", "null", ")", ";", "handleCallback", "(", "callback", ",", "err", ",", "result", ")", ";", "}", ")", ";", "}" ]
Evaluate JavaScript on the server @method @param {Db} db The Db instance. @param {Code} code JavaScript to execute on server. @param {(object|array)} parameters The parameters for the call. @param {object} [options] Optional settings. See Db.prototype.eval for a list of options. @param {Db~resultCallback} [callback] The results callback @deprecated Eval is deprecated on MongoDB 3.2 and forward
[ "Evaluate", "JavaScript", "on", "the", "server" ]
0afbbccf1bd7d437610c33cbd5523f01bc6bc6e5
https://github.com/mongodb/node-mongodb-native/blob/0afbbccf1bd7d437610c33cbd5523f01bc6bc6e5/lib/operations/db_ops.js#L442-L481
6,434
mongodb/node-mongodb-native
lib/operations/db_ops.js
executeDbAdminCommand
function executeDbAdminCommand(db, command, options, callback) { db.s.topology.command('admin.$cmd', command, options, (err, result) => { // Did the user destroy the topology if (db.serverConfig && db.serverConfig.isDestroyed()) { return callback(new MongoError('topology was destroyed')); } if (err) return handleCallback(callback, err); handleCallback(callback, null, result.result); }); }
javascript
function executeDbAdminCommand(db, command, options, callback) { db.s.topology.command('admin.$cmd', command, options, (err, result) => { // Did the user destroy the topology if (db.serverConfig && db.serverConfig.isDestroyed()) { return callback(new MongoError('topology was destroyed')); } if (err) return handleCallback(callback, err); handleCallback(callback, null, result.result); }); }
[ "function", "executeDbAdminCommand", "(", "db", ",", "command", ",", "options", ",", "callback", ")", "{", "db", ".", "s", ".", "topology", ".", "command", "(", "'admin.$cmd'", ",", "command", ",", "options", ",", "(", "err", ",", "result", ")", "=>", "{", "// Did the user destroy the topology", "if", "(", "db", ".", "serverConfig", "&&", "db", ".", "serverConfig", ".", "isDestroyed", "(", ")", ")", "{", "return", "callback", "(", "new", "MongoError", "(", "'topology was destroyed'", ")", ")", ";", "}", "if", "(", "err", ")", "return", "handleCallback", "(", "callback", ",", "err", ")", ";", "handleCallback", "(", "callback", ",", "null", ",", "result", ".", "result", ")", ";", "}", ")", ";", "}" ]
Runs a command on the database as admin. @method @param {Db} db The Db instance on which to execute the command. @param {object} command The command hash @param {object} [options] Optional settings. See Db.prototype.executeDbAdminCommand for a list of options. @param {Db~resultCallback} [callback] The command result callback
[ "Runs", "a", "command", "on", "the", "database", "as", "admin", "." ]
0afbbccf1bd7d437610c33cbd5523f01bc6bc6e5
https://github.com/mongodb/node-mongodb-native/blob/0afbbccf1bd7d437610c33cbd5523f01bc6bc6e5/lib/operations/db_ops.js#L529-L539
6,435
mongodb/node-mongodb-native
lib/operations/db_ops.js
indexInformation
function indexInformation(db, name, options, callback) { // If we specified full information const full = options['full'] == null ? false : options['full']; // Did the user destroy the topology if (db.serverConfig && db.serverConfig.isDestroyed()) return callback(new MongoError('topology was destroyed')); // Process all the results from the index command and collection function processResults(indexes) { // Contains all the information let info = {}; // Process all the indexes for (let i = 0; i < indexes.length; i++) { const index = indexes[i]; // Let's unpack the object info[index.name] = []; for (let name in index.key) { info[index.name].push([name, index.key[name]]); } } return info; } // Get the list of indexes of the specified collection db .collection(name) .listIndexes(options) .toArray((err, indexes) => { if (err) return callback(toError(err)); if (!Array.isArray(indexes)) return handleCallback(callback, null, []); if (full) return handleCallback(callback, null, indexes); handleCallback(callback, null, processResults(indexes)); }); }
javascript
function indexInformation(db, name, options, callback) { // If we specified full information const full = options['full'] == null ? false : options['full']; // Did the user destroy the topology if (db.serverConfig && db.serverConfig.isDestroyed()) return callback(new MongoError('topology was destroyed')); // Process all the results from the index command and collection function processResults(indexes) { // Contains all the information let info = {}; // Process all the indexes for (let i = 0; i < indexes.length; i++) { const index = indexes[i]; // Let's unpack the object info[index.name] = []; for (let name in index.key) { info[index.name].push([name, index.key[name]]); } } return info; } // Get the list of indexes of the specified collection db .collection(name) .listIndexes(options) .toArray((err, indexes) => { if (err) return callback(toError(err)); if (!Array.isArray(indexes)) return handleCallback(callback, null, []); if (full) return handleCallback(callback, null, indexes); handleCallback(callback, null, processResults(indexes)); }); }
[ "function", "indexInformation", "(", "db", ",", "name", ",", "options", ",", "callback", ")", "{", "// If we specified full information", "const", "full", "=", "options", "[", "'full'", "]", "==", "null", "?", "false", ":", "options", "[", "'full'", "]", ";", "// Did the user destroy the topology", "if", "(", "db", ".", "serverConfig", "&&", "db", ".", "serverConfig", ".", "isDestroyed", "(", ")", ")", "return", "callback", "(", "new", "MongoError", "(", "'topology was destroyed'", ")", ")", ";", "// Process all the results from the index command and collection", "function", "processResults", "(", "indexes", ")", "{", "// Contains all the information", "let", "info", "=", "{", "}", ";", "// Process all the indexes", "for", "(", "let", "i", "=", "0", ";", "i", "<", "indexes", ".", "length", ";", "i", "++", ")", "{", "const", "index", "=", "indexes", "[", "i", "]", ";", "// Let's unpack the object", "info", "[", "index", ".", "name", "]", "=", "[", "]", ";", "for", "(", "let", "name", "in", "index", ".", "key", ")", "{", "info", "[", "index", ".", "name", "]", ".", "push", "(", "[", "name", ",", "index", ".", "key", "[", "name", "]", "]", ")", ";", "}", "}", "return", "info", ";", "}", "// Get the list of indexes of the specified collection", "db", ".", "collection", "(", "name", ")", ".", "listIndexes", "(", "options", ")", ".", "toArray", "(", "(", "err", ",", "indexes", ")", "=>", "{", "if", "(", "err", ")", "return", "callback", "(", "toError", "(", "err", ")", ")", ";", "if", "(", "!", "Array", ".", "isArray", "(", "indexes", ")", ")", "return", "handleCallback", "(", "callback", ",", "null", ",", "[", "]", ")", ";", "if", "(", "full", ")", "return", "handleCallback", "(", "callback", ",", "null", ",", "indexes", ")", ";", "handleCallback", "(", "callback", ",", "null", ",", "processResults", "(", "indexes", ")", ")", ";", "}", ")", ";", "}" ]
Retrieves this collections index info. @method @param {Db} db The Db instance on which to retrieve the index info. @param {string} name The name of the collection. @param {object} [options] Optional settings. See Db.prototype.indexInformation for a list of options. @param {Db~resultCallback} [callback] The command result callback
[ "Retrieves", "this", "collections", "index", "info", "." ]
0afbbccf1bd7d437610c33cbd5523f01bc6bc6e5
https://github.com/mongodb/node-mongodb-native/blob/0afbbccf1bd7d437610c33cbd5523f01bc6bc6e5/lib/operations/db_ops.js#L550-L584
6,436
mongodb/node-mongodb-native
lib/operations/db_ops.js
processResults
function processResults(indexes) { // Contains all the information let info = {}; // Process all the indexes for (let i = 0; i < indexes.length; i++) { const index = indexes[i]; // Let's unpack the object info[index.name] = []; for (let name in index.key) { info[index.name].push([name, index.key[name]]); } } return info; }
javascript
function processResults(indexes) { // Contains all the information let info = {}; // Process all the indexes for (let i = 0; i < indexes.length; i++) { const index = indexes[i]; // Let's unpack the object info[index.name] = []; for (let name in index.key) { info[index.name].push([name, index.key[name]]); } } return info; }
[ "function", "processResults", "(", "indexes", ")", "{", "// Contains all the information", "let", "info", "=", "{", "}", ";", "// Process all the indexes", "for", "(", "let", "i", "=", "0", ";", "i", "<", "indexes", ".", "length", ";", "i", "++", ")", "{", "const", "index", "=", "indexes", "[", "i", "]", ";", "// Let's unpack the object", "info", "[", "index", ".", "name", "]", "=", "[", "]", ";", "for", "(", "let", "name", "in", "index", ".", "key", ")", "{", "info", "[", "index", ".", "name", "]", ".", "push", "(", "[", "name", ",", "index", ".", "key", "[", "name", "]", "]", ")", ";", "}", "}", "return", "info", ";", "}" ]
Process all the results from the index command and collection
[ "Process", "all", "the", "results", "from", "the", "index", "command", "and", "collection" ]
0afbbccf1bd7d437610c33cbd5523f01bc6bc6e5
https://github.com/mongodb/node-mongodb-native/blob/0afbbccf1bd7d437610c33cbd5523f01bc6bc6e5/lib/operations/db_ops.js#L558-L572
6,437
mongodb/node-mongodb-native
lib/operations/db_ops.js
listCollectionsTransforms
function listCollectionsTransforms(databaseName) { const matching = `${databaseName}.`; return { doc: doc => { const index = doc.name.indexOf(matching); // Remove database name if available if (doc.name && index === 0) { doc.name = doc.name.substr(index + matching.length); } return doc; } }; }
javascript
function listCollectionsTransforms(databaseName) { const matching = `${databaseName}.`; return { doc: doc => { const index = doc.name.indexOf(matching); // Remove database name if available if (doc.name && index === 0) { doc.name = doc.name.substr(index + matching.length); } return doc; } }; }
[ "function", "listCollectionsTransforms", "(", "databaseName", ")", "{", "const", "matching", "=", "`", "${", "databaseName", "}", "`", ";", "return", "{", "doc", ":", "doc", "=>", "{", "const", "index", "=", "doc", ".", "name", ".", "indexOf", "(", "matching", ")", ";", "// Remove database name if available", "if", "(", "doc", ".", "name", "&&", "index", "===", "0", ")", "{", "doc", ".", "name", "=", "doc", ".", "name", ".", "substr", "(", "index", "+", "matching", ".", "length", ")", ";", "}", "return", "doc", ";", "}", "}", ";", "}" ]
Transformation methods for cursor results
[ "Transformation", "methods", "for", "cursor", "results" ]
0afbbccf1bd7d437610c33cbd5523f01bc6bc6e5
https://github.com/mongodb/node-mongodb-native/blob/0afbbccf1bd7d437610c33cbd5523f01bc6bc6e5/lib/operations/db_ops.js#L587-L601
6,438
mongodb/node-mongodb-native
lib/operations/db_ops.js
profilingInfo
function profilingInfo(db, options, callback) { try { db .collection('system.profile') .find({}, options) .toArray(callback); } catch (err) { return callback(err, null); } }
javascript
function profilingInfo(db, options, callback) { try { db .collection('system.profile') .find({}, options) .toArray(callback); } catch (err) { return callback(err, null); } }
[ "function", "profilingInfo", "(", "db", ",", "options", ",", "callback", ")", "{", "try", "{", "db", ".", "collection", "(", "'system.profile'", ")", ".", "find", "(", "{", "}", ",", "options", ")", ".", "toArray", "(", "callback", ")", ";", "}", "catch", "(", "err", ")", "{", "return", "callback", "(", "err", ",", "null", ")", ";", "}", "}" ]
Retrieve the current profiling information for MongoDB @method @param {Db} db The Db instance on which to retrieve the profiling info. @param {Object} [options] Optional settings. See Db.protoype.profilingInfo for a list of options. @param {Db~resultCallback} [callback] The command result callback. @deprecated Query the system.profile collection directly.
[ "Retrieve", "the", "current", "profiling", "information", "for", "MongoDB" ]
0afbbccf1bd7d437610c33cbd5523f01bc6bc6e5
https://github.com/mongodb/node-mongodb-native/blob/0afbbccf1bd7d437610c33cbd5523f01bc6bc6e5/lib/operations/db_ops.js#L612-L621
6,439
mongodb/node-mongodb-native
lib/operations/db_ops.js
profilingLevel
function profilingLevel(db, options, callback) { executeCommand(db, { profile: -1 }, options, (err, doc) => { if (err == null && doc.ok === 1) { const was = doc.was; if (was === 0) return callback(null, 'off'); if (was === 1) return callback(null, 'slow_only'); if (was === 2) return callback(null, 'all'); return callback(new Error('Error: illegal profiling level value ' + was), null); } else { err != null ? callback(err, null) : callback(new Error('Error with profile command'), null); } }); }
javascript
function profilingLevel(db, options, callback) { executeCommand(db, { profile: -1 }, options, (err, doc) => { if (err == null && doc.ok === 1) { const was = doc.was; if (was === 0) return callback(null, 'off'); if (was === 1) return callback(null, 'slow_only'); if (was === 2) return callback(null, 'all'); return callback(new Error('Error: illegal profiling level value ' + was), null); } else { err != null ? callback(err, null) : callback(new Error('Error with profile command'), null); } }); }
[ "function", "profilingLevel", "(", "db", ",", "options", ",", "callback", ")", "{", "executeCommand", "(", "db", ",", "{", "profile", ":", "-", "1", "}", ",", "options", ",", "(", "err", ",", "doc", ")", "=>", "{", "if", "(", "err", "==", "null", "&&", "doc", ".", "ok", "===", "1", ")", "{", "const", "was", "=", "doc", ".", "was", ";", "if", "(", "was", "===", "0", ")", "return", "callback", "(", "null", ",", "'off'", ")", ";", "if", "(", "was", "===", "1", ")", "return", "callback", "(", "null", ",", "'slow_only'", ")", ";", "if", "(", "was", "===", "2", ")", "return", "callback", "(", "null", ",", "'all'", ")", ";", "return", "callback", "(", "new", "Error", "(", "'Error: illegal profiling level value '", "+", "was", ")", ",", "null", ")", ";", "}", "else", "{", "err", "!=", "null", "?", "callback", "(", "err", ",", "null", ")", ":", "callback", "(", "new", "Error", "(", "'Error with profile command'", ")", ",", "null", ")", ";", "}", "}", ")", ";", "}" ]
Retrieve the current profiling level for MongoDB @method @param {Db} db The Db instance on which to retrieve the profiling level. @param {Object} [options] Optional settings. See Db.prototype.profilingLevel for a list of options. @param {Db~resultCallback} [callback] The command result callback
[ "Retrieve", "the", "current", "profiling", "level", "for", "MongoDB" ]
0afbbccf1bd7d437610c33cbd5523f01bc6bc6e5
https://github.com/mongodb/node-mongodb-native/blob/0afbbccf1bd7d437610c33cbd5523f01bc6bc6e5/lib/operations/db_ops.js#L631-L643
6,440
mongodb/node-mongodb-native
lib/operations/db_ops.js
removeUser
function removeUser(db, username, options, callback) { let Db = loadDb(); // Attempt to execute command executeAuthRemoveUserCommand(db, username, options, (err, result) => { if (err && err.code === -5000) { const finalOptions = applyWriteConcern(Object.assign({}, options), { db }, options); // If we have another db set const db = options.dbName ? new Db(options.dbName, db.s.topology, db.s.options) : db; // Fetch a user collection const collection = db.collection(CONSTANTS.SYSTEM_USER_COLLECTION); // Locate the user findOne(collection, { user: username }, finalOptions, (err, user) => { if (user == null) return handleCallback(callback, err, false); remove(collection, { user: username }, finalOptions, err => { handleCallback(callback, err, true); }); }); return; } if (err) return handleCallback(callback, err); handleCallback(callback, err, result); }); }
javascript
function removeUser(db, username, options, callback) { let Db = loadDb(); // Attempt to execute command executeAuthRemoveUserCommand(db, username, options, (err, result) => { if (err && err.code === -5000) { const finalOptions = applyWriteConcern(Object.assign({}, options), { db }, options); // If we have another db set const db = options.dbName ? new Db(options.dbName, db.s.topology, db.s.options) : db; // Fetch a user collection const collection = db.collection(CONSTANTS.SYSTEM_USER_COLLECTION); // Locate the user findOne(collection, { user: username }, finalOptions, (err, user) => { if (user == null) return handleCallback(callback, err, false); remove(collection, { user: username }, finalOptions, err => { handleCallback(callback, err, true); }); }); return; } if (err) return handleCallback(callback, err); handleCallback(callback, err, result); }); }
[ "function", "removeUser", "(", "db", ",", "username", ",", "options", ",", "callback", ")", "{", "let", "Db", "=", "loadDb", "(", ")", ";", "// Attempt to execute command", "executeAuthRemoveUserCommand", "(", "db", ",", "username", ",", "options", ",", "(", "err", ",", "result", ")", "=>", "{", "if", "(", "err", "&&", "err", ".", "code", "===", "-", "5000", ")", "{", "const", "finalOptions", "=", "applyWriteConcern", "(", "Object", ".", "assign", "(", "{", "}", ",", "options", ")", ",", "{", "db", "}", ",", "options", ")", ";", "// If we have another db set", "const", "db", "=", "options", ".", "dbName", "?", "new", "Db", "(", "options", ".", "dbName", ",", "db", ".", "s", ".", "topology", ",", "db", ".", "s", ".", "options", ")", ":", "db", ";", "// Fetch a user collection", "const", "collection", "=", "db", ".", "collection", "(", "CONSTANTS", ".", "SYSTEM_USER_COLLECTION", ")", ";", "// Locate the user", "findOne", "(", "collection", ",", "{", "user", ":", "username", "}", ",", "finalOptions", ",", "(", "err", ",", "user", ")", "=>", "{", "if", "(", "user", "==", "null", ")", "return", "handleCallback", "(", "callback", ",", "err", ",", "false", ")", ";", "remove", "(", "collection", ",", "{", "user", ":", "username", "}", ",", "finalOptions", ",", "err", "=>", "{", "handleCallback", "(", "callback", ",", "err", ",", "true", ")", ";", "}", ")", ";", "}", ")", ";", "return", ";", "}", "if", "(", "err", ")", "return", "handleCallback", "(", "callback", ",", "err", ")", ";", "handleCallback", "(", "callback", ",", "err", ",", "result", ")", ";", "}", ")", ";", "}" ]
Remove a user from a database @method @param {Db} db The Db instance on which to remove the user. @param {string} username The username. @param {object} [options] Optional settings. See Db.prototype.removeUser for a list of options. @param {Db~resultCallback} [callback] The command result callback
[ "Remove", "a", "user", "from", "a", "database" ]
0afbbccf1bd7d437610c33cbd5523f01bc6bc6e5
https://github.com/mongodb/node-mongodb-native/blob/0afbbccf1bd7d437610c33cbd5523f01bc6bc6e5/lib/operations/db_ops.js#L654-L681
6,441
mongodb/node-mongodb-native
lib/operations/db_ops.js
setProfilingLevel
function setProfilingLevel(db, level, options, callback) { const command = {}; let profile = 0; if (level === 'off') { profile = 0; } else if (level === 'slow_only') { profile = 1; } else if (level === 'all') { profile = 2; } else { return callback(new Error('Error: illegal profiling level value ' + level)); } // Set up the profile number command['profile'] = profile; executeCommand(db, command, options, (err, doc) => { if (err == null && doc.ok === 1) return callback(null, level); return err != null ? callback(err, null) : callback(new Error('Error with profile command'), null); }); }
javascript
function setProfilingLevel(db, level, options, callback) { const command = {}; let profile = 0; if (level === 'off') { profile = 0; } else if (level === 'slow_only') { profile = 1; } else if (level === 'all') { profile = 2; } else { return callback(new Error('Error: illegal profiling level value ' + level)); } // Set up the profile number command['profile'] = profile; executeCommand(db, command, options, (err, doc) => { if (err == null && doc.ok === 1) return callback(null, level); return err != null ? callback(err, null) : callback(new Error('Error with profile command'), null); }); }
[ "function", "setProfilingLevel", "(", "db", ",", "level", ",", "options", ",", "callback", ")", "{", "const", "command", "=", "{", "}", ";", "let", "profile", "=", "0", ";", "if", "(", "level", "===", "'off'", ")", "{", "profile", "=", "0", ";", "}", "else", "if", "(", "level", "===", "'slow_only'", ")", "{", "profile", "=", "1", ";", "}", "else", "if", "(", "level", "===", "'all'", ")", "{", "profile", "=", "2", ";", "}", "else", "{", "return", "callback", "(", "new", "Error", "(", "'Error: illegal profiling level value '", "+", "level", ")", ")", ";", "}", "// Set up the profile number", "command", "[", "'profile'", "]", "=", "profile", ";", "executeCommand", "(", "db", ",", "command", ",", "options", ",", "(", "err", ",", "doc", ")", "=>", "{", "if", "(", "err", "==", "null", "&&", "doc", ".", "ok", "===", "1", ")", "return", "callback", "(", "null", ",", "level", ")", ";", "return", "err", "!=", "null", "?", "callback", "(", "err", ",", "null", ")", ":", "callback", "(", "new", "Error", "(", "'Error with profile command'", ")", ",", "null", ")", ";", "}", ")", ";", "}" ]
Set the current profiling level of MongoDB @method @param {Db} db The Db instance on which to execute the command. @param {string} level The new profiling level (off, slow_only, all). @param {Object} [options] Optional settings. See Db.prototype.setProfilingLevel for a list of options. @param {Db~resultCallback} [callback] The command result callback.
[ "Set", "the", "current", "profiling", "level", "of", "MongoDB" ]
0afbbccf1bd7d437610c33cbd5523f01bc6bc6e5
https://github.com/mongodb/node-mongodb-native/blob/0afbbccf1bd7d437610c33cbd5523f01bc6bc6e5/lib/operations/db_ops.js#L692-L715
6,442
mongodb/node-mongodb-native
lib/operations/db_ops.js
validateDatabaseName
function validateDatabaseName(databaseName) { if (typeof databaseName !== 'string') throw MongoError.create({ message: 'database name must be a string', driver: true }); if (databaseName.length === 0) throw MongoError.create({ message: 'database name cannot be the empty string', driver: true }); if (databaseName === '$external') return; const invalidChars = [' ', '.', '$', '/', '\\']; for (let i = 0; i < invalidChars.length; i++) { if (databaseName.indexOf(invalidChars[i]) !== -1) throw MongoError.create({ message: "database names cannot contain the character '" + invalidChars[i] + "'", driver: true }); } }
javascript
function validateDatabaseName(databaseName) { if (typeof databaseName !== 'string') throw MongoError.create({ message: 'database name must be a string', driver: true }); if (databaseName.length === 0) throw MongoError.create({ message: 'database name cannot be the empty string', driver: true }); if (databaseName === '$external') return; const invalidChars = [' ', '.', '$', '/', '\\']; for (let i = 0; i < invalidChars.length; i++) { if (databaseName.indexOf(invalidChars[i]) !== -1) throw MongoError.create({ message: "database names cannot contain the character '" + invalidChars[i] + "'", driver: true }); } }
[ "function", "validateDatabaseName", "(", "databaseName", ")", "{", "if", "(", "typeof", "databaseName", "!==", "'string'", ")", "throw", "MongoError", ".", "create", "(", "{", "message", ":", "'database name must be a string'", ",", "driver", ":", "true", "}", ")", ";", "if", "(", "databaseName", ".", "length", "===", "0", ")", "throw", "MongoError", ".", "create", "(", "{", "message", ":", "'database name cannot be the empty string'", ",", "driver", ":", "true", "}", ")", ";", "if", "(", "databaseName", "===", "'$external'", ")", "return", ";", "const", "invalidChars", "=", "[", "' '", ",", "'.'", ",", "'$'", ",", "'/'", ",", "'\\\\'", "]", ";", "for", "(", "let", "i", "=", "0", ";", "i", "<", "invalidChars", ".", "length", ";", "i", "++", ")", "{", "if", "(", "databaseName", ".", "indexOf", "(", "invalidChars", "[", "i", "]", ")", "!==", "-", "1", ")", "throw", "MongoError", ".", "create", "(", "{", "message", ":", "\"database names cannot contain the character '\"", "+", "invalidChars", "[", "i", "]", "+", "\"'\"", ",", "driver", ":", "true", "}", ")", ";", "}", "}" ]
Validate the database name
[ "Validate", "the", "database", "name" ]
0afbbccf1bd7d437610c33cbd5523f01bc6bc6e5
https://github.com/mongodb/node-mongodb-native/blob/0afbbccf1bd7d437610c33cbd5523f01bc6bc6e5/lib/operations/db_ops.js#L718-L733
6,443
mongodb/node-mongodb-native
lib/operations/db_ops.js
createCreateIndexCommand
function createCreateIndexCommand(db, name, fieldOrSpec, options) { const indexParameters = parseIndexOptions(fieldOrSpec); const fieldHash = indexParameters.fieldHash; // Generate the index name const indexName = typeof options.name === 'string' ? options.name : indexParameters.name; const selector = { ns: db.databaseName + '.' + name, key: fieldHash, name: indexName }; // Ensure we have a correct finalUnique const finalUnique = options == null || 'object' === typeof options ? false : options; // Set up options options = options == null || typeof options === 'boolean' ? {} : options; // Add all the options const keysToOmit = Object.keys(selector); for (let optionName in options) { if (keysToOmit.indexOf(optionName) === -1) { selector[optionName] = options[optionName]; } } if (selector['unique'] == null) selector['unique'] = finalUnique; // Remove any write concern operations const removeKeys = ['w', 'wtimeout', 'j', 'fsync', 'readPreference', 'session']; for (let i = 0; i < removeKeys.length; i++) { delete selector[removeKeys[i]]; } // Return the command creation selector return selector; }
javascript
function createCreateIndexCommand(db, name, fieldOrSpec, options) { const indexParameters = parseIndexOptions(fieldOrSpec); const fieldHash = indexParameters.fieldHash; // Generate the index name const indexName = typeof options.name === 'string' ? options.name : indexParameters.name; const selector = { ns: db.databaseName + '.' + name, key: fieldHash, name: indexName }; // Ensure we have a correct finalUnique const finalUnique = options == null || 'object' === typeof options ? false : options; // Set up options options = options == null || typeof options === 'boolean' ? {} : options; // Add all the options const keysToOmit = Object.keys(selector); for (let optionName in options) { if (keysToOmit.indexOf(optionName) === -1) { selector[optionName] = options[optionName]; } } if (selector['unique'] == null) selector['unique'] = finalUnique; // Remove any write concern operations const removeKeys = ['w', 'wtimeout', 'j', 'fsync', 'readPreference', 'session']; for (let i = 0; i < removeKeys.length; i++) { delete selector[removeKeys[i]]; } // Return the command creation selector return selector; }
[ "function", "createCreateIndexCommand", "(", "db", ",", "name", ",", "fieldOrSpec", ",", "options", ")", "{", "const", "indexParameters", "=", "parseIndexOptions", "(", "fieldOrSpec", ")", ";", "const", "fieldHash", "=", "indexParameters", ".", "fieldHash", ";", "// Generate the index name", "const", "indexName", "=", "typeof", "options", ".", "name", "===", "'string'", "?", "options", ".", "name", ":", "indexParameters", ".", "name", ";", "const", "selector", "=", "{", "ns", ":", "db", ".", "databaseName", "+", "'.'", "+", "name", ",", "key", ":", "fieldHash", ",", "name", ":", "indexName", "}", ";", "// Ensure we have a correct finalUnique", "const", "finalUnique", "=", "options", "==", "null", "||", "'object'", "===", "typeof", "options", "?", "false", ":", "options", ";", "// Set up options", "options", "=", "options", "==", "null", "||", "typeof", "options", "===", "'boolean'", "?", "{", "}", ":", "options", ";", "// Add all the options", "const", "keysToOmit", "=", "Object", ".", "keys", "(", "selector", ")", ";", "for", "(", "let", "optionName", "in", "options", ")", "{", "if", "(", "keysToOmit", ".", "indexOf", "(", "optionName", ")", "===", "-", "1", ")", "{", "selector", "[", "optionName", "]", "=", "options", "[", "optionName", "]", ";", "}", "}", "if", "(", "selector", "[", "'unique'", "]", "==", "null", ")", "selector", "[", "'unique'", "]", "=", "finalUnique", ";", "// Remove any write concern operations", "const", "removeKeys", "=", "[", "'w'", ",", "'wtimeout'", ",", "'j'", ",", "'fsync'", ",", "'readPreference'", ",", "'session'", "]", ";", "for", "(", "let", "i", "=", "0", ";", "i", "<", "removeKeys", ".", "length", ";", "i", "++", ")", "{", "delete", "selector", "[", "removeKeys", "[", "i", "]", "]", ";", "}", "// Return the command creation selector", "return", "selector", ";", "}" ]
Create the command object for Db.prototype.createIndex. @param {Db} db The Db instance on which to create the command. @param {string} name Name of the collection to create the index on. @param {(string|object)} fieldOrSpec Defines the index. @param {Object} [options] Optional settings. See Db.prototype.createIndex for a list of options. @return {Object} The insert command object.
[ "Create", "the", "command", "object", "for", "Db", ".", "prototype", ".", "createIndex", "." ]
0afbbccf1bd7d437610c33cbd5523f01bc6bc6e5
https://github.com/mongodb/node-mongodb-native/blob/0afbbccf1bd7d437610c33cbd5523f01bc6bc6e5/lib/operations/db_ops.js#L744-L779
6,444
mongodb/node-mongodb-native
lib/operations/db_ops.js
createIndexUsingCreateIndexes
function createIndexUsingCreateIndexes(db, name, fieldOrSpec, options, callback) { // Build the index const indexParameters = parseIndexOptions(fieldOrSpec); // Generate the index name const indexName = typeof options.name === 'string' ? options.name : indexParameters.name; // Set up the index const indexes = [{ name: indexName, key: indexParameters.fieldHash }]; // merge all the options const keysToOmit = Object.keys(indexes[0]).concat([ 'writeConcern', 'w', 'wtimeout', 'j', 'fsync', 'readPreference', 'session' ]); for (let optionName in options) { if (keysToOmit.indexOf(optionName) === -1) { indexes[0][optionName] = options[optionName]; } } // Get capabilities const capabilities = db.s.topology.capabilities(); // Did the user pass in a collation, check if our write server supports it if (indexes[0].collation && capabilities && !capabilities.commandsTakeCollation) { // Create a new error const error = new MongoError('server/primary/mongos does not support collation'); error.code = 67; // Return the error return callback(error); } // Create command, apply write concern to command const cmd = applyWriteConcern({ createIndexes: name, indexes }, { db }, options); // ReadPreference primary options.readPreference = ReadPreference.PRIMARY; // Build the command executeCommand(db, cmd, options, (err, result) => { if (err) return handleCallback(callback, err, null); if (result.ok === 0) return handleCallback(callback, toError(result), null); // Return the indexName for backward compatibility handleCallback(callback, null, indexName); }); }
javascript
function createIndexUsingCreateIndexes(db, name, fieldOrSpec, options, callback) { // Build the index const indexParameters = parseIndexOptions(fieldOrSpec); // Generate the index name const indexName = typeof options.name === 'string' ? options.name : indexParameters.name; // Set up the index const indexes = [{ name: indexName, key: indexParameters.fieldHash }]; // merge all the options const keysToOmit = Object.keys(indexes[0]).concat([ 'writeConcern', 'w', 'wtimeout', 'j', 'fsync', 'readPreference', 'session' ]); for (let optionName in options) { if (keysToOmit.indexOf(optionName) === -1) { indexes[0][optionName] = options[optionName]; } } // Get capabilities const capabilities = db.s.topology.capabilities(); // Did the user pass in a collation, check if our write server supports it if (indexes[0].collation && capabilities && !capabilities.commandsTakeCollation) { // Create a new error const error = new MongoError('server/primary/mongos does not support collation'); error.code = 67; // Return the error return callback(error); } // Create command, apply write concern to command const cmd = applyWriteConcern({ createIndexes: name, indexes }, { db }, options); // ReadPreference primary options.readPreference = ReadPreference.PRIMARY; // Build the command executeCommand(db, cmd, options, (err, result) => { if (err) return handleCallback(callback, err, null); if (result.ok === 0) return handleCallback(callback, toError(result), null); // Return the indexName for backward compatibility handleCallback(callback, null, indexName); }); }
[ "function", "createIndexUsingCreateIndexes", "(", "db", ",", "name", ",", "fieldOrSpec", ",", "options", ",", "callback", ")", "{", "// Build the index", "const", "indexParameters", "=", "parseIndexOptions", "(", "fieldOrSpec", ")", ";", "// Generate the index name", "const", "indexName", "=", "typeof", "options", ".", "name", "===", "'string'", "?", "options", ".", "name", ":", "indexParameters", ".", "name", ";", "// Set up the index", "const", "indexes", "=", "[", "{", "name", ":", "indexName", ",", "key", ":", "indexParameters", ".", "fieldHash", "}", "]", ";", "// merge all the options", "const", "keysToOmit", "=", "Object", ".", "keys", "(", "indexes", "[", "0", "]", ")", ".", "concat", "(", "[", "'writeConcern'", ",", "'w'", ",", "'wtimeout'", ",", "'j'", ",", "'fsync'", ",", "'readPreference'", ",", "'session'", "]", ")", ";", "for", "(", "let", "optionName", "in", "options", ")", "{", "if", "(", "keysToOmit", ".", "indexOf", "(", "optionName", ")", "===", "-", "1", ")", "{", "indexes", "[", "0", "]", "[", "optionName", "]", "=", "options", "[", "optionName", "]", ";", "}", "}", "// Get capabilities", "const", "capabilities", "=", "db", ".", "s", ".", "topology", ".", "capabilities", "(", ")", ";", "// Did the user pass in a collation, check if our write server supports it", "if", "(", "indexes", "[", "0", "]", ".", "collation", "&&", "capabilities", "&&", "!", "capabilities", ".", "commandsTakeCollation", ")", "{", "// Create a new error", "const", "error", "=", "new", "MongoError", "(", "'server/primary/mongos does not support collation'", ")", ";", "error", ".", "code", "=", "67", ";", "// Return the error", "return", "callback", "(", "error", ")", ";", "}", "// Create command, apply write concern to command", "const", "cmd", "=", "applyWriteConcern", "(", "{", "createIndexes", ":", "name", ",", "indexes", "}", ",", "{", "db", "}", ",", "options", ")", ";", "// ReadPreference primary", "options", ".", "readPreference", "=", "ReadPreference", ".", "PRIMARY", ";", "// Build the command", "executeCommand", "(", "db", ",", "cmd", ",", "options", ",", "(", "err", ",", "result", ")", "=>", "{", "if", "(", "err", ")", "return", "handleCallback", "(", "callback", ",", "err", ",", "null", ")", ";", "if", "(", "result", ".", "ok", "===", "0", ")", "return", "handleCallback", "(", "callback", ",", "toError", "(", "result", ")", ",", "null", ")", ";", "// Return the indexName for backward compatibility", "handleCallback", "(", "callback", ",", "null", ",", "indexName", ")", ";", "}", ")", ";", "}" ]
Create index using the createIndexes command. @param {Db} db The Db instance on which to execute the command. @param {string} name Name of the collection to create the index on. @param {(string|object)} fieldOrSpec Defines the index. @param {Object} [options] Optional settings. See Db.prototype.createIndex for a list of options. @param {Db~resultCallback} [callback] The command result callback.
[ "Create", "index", "using", "the", "createIndexes", "command", "." ]
0afbbccf1bd7d437610c33cbd5523f01bc6bc6e5
https://github.com/mongodb/node-mongodb-native/blob/0afbbccf1bd7d437610c33cbd5523f01bc6bc6e5/lib/operations/db_ops.js#L790-L839
6,445
mongodb/node-mongodb-native
lib/operations/db_ops.js
executeAuthCreateUserCommand
function executeAuthCreateUserCommand(db, username, password, options, callback) { // Special case where there is no password ($external users) if (typeof username === 'string' && password != null && typeof password === 'object') { options = password; password = null; } // Unpack all options if (typeof options === 'function') { callback = options; options = {}; } // Error out if we digestPassword set if (options.digestPassword != null) { return callback( toError( "The digestPassword option is not supported via add_user. Please use db.command('createUser', ...) instead for this option." ) ); } // Get additional values const customData = options.customData != null ? options.customData : {}; let roles = Array.isArray(options.roles) ? options.roles : []; const maxTimeMS = typeof options.maxTimeMS === 'number' ? options.maxTimeMS : null; // If not roles defined print deprecated message if (roles.length === 0) { console.log('Creating a user without roles is deprecated in MongoDB >= 2.6'); } // Get the error options const commandOptions = { writeCommand: true }; if (options['dbName']) commandOptions.dbName = options['dbName']; // Add maxTimeMS to options if set if (maxTimeMS != null) commandOptions.maxTimeMS = maxTimeMS; // Check the db name and add roles if needed if ( (db.databaseName.toLowerCase() === 'admin' || options.dbName === 'admin') && !Array.isArray(options.roles) ) { roles = ['root']; } else if (!Array.isArray(options.roles)) { roles = ['dbOwner']; } const digestPassword = db.s.topology.lastIsMaster().maxWireVersion >= 7; // Build the command to execute let command = { createUser: username, customData: customData, roles: roles, digestPassword }; // Apply write concern to command command = applyWriteConcern(command, { db }, options); let userPassword = password; if (!digestPassword) { // Use node md5 generator const md5 = crypto.createHash('md5'); // Generate keys used for authentication md5.update(username + ':mongo:' + password); userPassword = md5.digest('hex'); } // No password if (typeof password === 'string') { command.pwd = userPassword; } // Force write using primary commandOptions.readPreference = ReadPreference.primary; // Execute the command executeCommand(db, command, commandOptions, (err, result) => { if (err && err.ok === 0 && err.code === undefined) return handleCallback(callback, { code: -5000 }, null); if (err) return handleCallback(callback, err, null); handleCallback( callback, !result.ok ? toError(result) : null, result.ok ? [{ user: username, pwd: '' }] : null ); }); }
javascript
function executeAuthCreateUserCommand(db, username, password, options, callback) { // Special case where there is no password ($external users) if (typeof username === 'string' && password != null && typeof password === 'object') { options = password; password = null; } // Unpack all options if (typeof options === 'function') { callback = options; options = {}; } // Error out if we digestPassword set if (options.digestPassword != null) { return callback( toError( "The digestPassword option is not supported via add_user. Please use db.command('createUser', ...) instead for this option." ) ); } // Get additional values const customData = options.customData != null ? options.customData : {}; let roles = Array.isArray(options.roles) ? options.roles : []; const maxTimeMS = typeof options.maxTimeMS === 'number' ? options.maxTimeMS : null; // If not roles defined print deprecated message if (roles.length === 0) { console.log('Creating a user without roles is deprecated in MongoDB >= 2.6'); } // Get the error options const commandOptions = { writeCommand: true }; if (options['dbName']) commandOptions.dbName = options['dbName']; // Add maxTimeMS to options if set if (maxTimeMS != null) commandOptions.maxTimeMS = maxTimeMS; // Check the db name and add roles if needed if ( (db.databaseName.toLowerCase() === 'admin' || options.dbName === 'admin') && !Array.isArray(options.roles) ) { roles = ['root']; } else if (!Array.isArray(options.roles)) { roles = ['dbOwner']; } const digestPassword = db.s.topology.lastIsMaster().maxWireVersion >= 7; // Build the command to execute let command = { createUser: username, customData: customData, roles: roles, digestPassword }; // Apply write concern to command command = applyWriteConcern(command, { db }, options); let userPassword = password; if (!digestPassword) { // Use node md5 generator const md5 = crypto.createHash('md5'); // Generate keys used for authentication md5.update(username + ':mongo:' + password); userPassword = md5.digest('hex'); } // No password if (typeof password === 'string') { command.pwd = userPassword; } // Force write using primary commandOptions.readPreference = ReadPreference.primary; // Execute the command executeCommand(db, command, commandOptions, (err, result) => { if (err && err.ok === 0 && err.code === undefined) return handleCallback(callback, { code: -5000 }, null); if (err) return handleCallback(callback, err, null); handleCallback( callback, !result.ok ? toError(result) : null, result.ok ? [{ user: username, pwd: '' }] : null ); }); }
[ "function", "executeAuthCreateUserCommand", "(", "db", ",", "username", ",", "password", ",", "options", ",", "callback", ")", "{", "// Special case where there is no password ($external users)", "if", "(", "typeof", "username", "===", "'string'", "&&", "password", "!=", "null", "&&", "typeof", "password", "===", "'object'", ")", "{", "options", "=", "password", ";", "password", "=", "null", ";", "}", "// Unpack all options", "if", "(", "typeof", "options", "===", "'function'", ")", "{", "callback", "=", "options", ";", "options", "=", "{", "}", ";", "}", "// Error out if we digestPassword set", "if", "(", "options", ".", "digestPassword", "!=", "null", ")", "{", "return", "callback", "(", "toError", "(", "\"The digestPassword option is not supported via add_user. Please use db.command('createUser', ...) instead for this option.\"", ")", ")", ";", "}", "// Get additional values", "const", "customData", "=", "options", ".", "customData", "!=", "null", "?", "options", ".", "customData", ":", "{", "}", ";", "let", "roles", "=", "Array", ".", "isArray", "(", "options", ".", "roles", ")", "?", "options", ".", "roles", ":", "[", "]", ";", "const", "maxTimeMS", "=", "typeof", "options", ".", "maxTimeMS", "===", "'number'", "?", "options", ".", "maxTimeMS", ":", "null", ";", "// If not roles defined print deprecated message", "if", "(", "roles", ".", "length", "===", "0", ")", "{", "console", ".", "log", "(", "'Creating a user without roles is deprecated in MongoDB >= 2.6'", ")", ";", "}", "// Get the error options", "const", "commandOptions", "=", "{", "writeCommand", ":", "true", "}", ";", "if", "(", "options", "[", "'dbName'", "]", ")", "commandOptions", ".", "dbName", "=", "options", "[", "'dbName'", "]", ";", "// Add maxTimeMS to options if set", "if", "(", "maxTimeMS", "!=", "null", ")", "commandOptions", ".", "maxTimeMS", "=", "maxTimeMS", ";", "// Check the db name and add roles if needed", "if", "(", "(", "db", ".", "databaseName", ".", "toLowerCase", "(", ")", "===", "'admin'", "||", "options", ".", "dbName", "===", "'admin'", ")", "&&", "!", "Array", ".", "isArray", "(", "options", ".", "roles", ")", ")", "{", "roles", "=", "[", "'root'", "]", ";", "}", "else", "if", "(", "!", "Array", ".", "isArray", "(", "options", ".", "roles", ")", ")", "{", "roles", "=", "[", "'dbOwner'", "]", ";", "}", "const", "digestPassword", "=", "db", ".", "s", ".", "topology", ".", "lastIsMaster", "(", ")", ".", "maxWireVersion", ">=", "7", ";", "// Build the command to execute", "let", "command", "=", "{", "createUser", ":", "username", ",", "customData", ":", "customData", ",", "roles", ":", "roles", ",", "digestPassword", "}", ";", "// Apply write concern to command", "command", "=", "applyWriteConcern", "(", "command", ",", "{", "db", "}", ",", "options", ")", ";", "let", "userPassword", "=", "password", ";", "if", "(", "!", "digestPassword", ")", "{", "// Use node md5 generator", "const", "md5", "=", "crypto", ".", "createHash", "(", "'md5'", ")", ";", "// Generate keys used for authentication", "md5", ".", "update", "(", "username", "+", "':mongo:'", "+", "password", ")", ";", "userPassword", "=", "md5", ".", "digest", "(", "'hex'", ")", ";", "}", "// No password", "if", "(", "typeof", "password", "===", "'string'", ")", "{", "command", ".", "pwd", "=", "userPassword", ";", "}", "// Force write using primary", "commandOptions", ".", "readPreference", "=", "ReadPreference", ".", "primary", ";", "// Execute the command", "executeCommand", "(", "db", ",", "command", ",", "commandOptions", ",", "(", "err", ",", "result", ")", "=>", "{", "if", "(", "err", "&&", "err", ".", "ok", "===", "0", "&&", "err", ".", "code", "===", "undefined", ")", "return", "handleCallback", "(", "callback", ",", "{", "code", ":", "-", "5000", "}", ",", "null", ")", ";", "if", "(", "err", ")", "return", "handleCallback", "(", "callback", ",", "err", ",", "null", ")", ";", "handleCallback", "(", "callback", ",", "!", "result", ".", "ok", "?", "toError", "(", "result", ")", ":", "null", ",", "result", ".", "ok", "?", "[", "{", "user", ":", "username", ",", "pwd", ":", "''", "}", "]", ":", "null", ")", ";", "}", ")", ";", "}" ]
Run the createUser command. @param {Db} db The Db instance on which to execute the command. @param {string} username The username of the user to add. @param {string} password The password of the user to add. @param {object} [options] Optional settings. See Db.prototype.addUser for a list of options. @param {Db~resultCallback} [callback] The command result callback
[ "Run", "the", "createUser", "command", "." ]
0afbbccf1bd7d437610c33cbd5523f01bc6bc6e5
https://github.com/mongodb/node-mongodb-native/blob/0afbbccf1bd7d437610c33cbd5523f01bc6bc6e5/lib/operations/db_ops.js#L850-L941
6,446
mongodb/node-mongodb-native
lib/operations/db_ops.js
executeAuthRemoveUserCommand
function executeAuthRemoveUserCommand(db, username, options, callback) { if (typeof options === 'function') (callback = options), (options = {}); options = options || {}; // Did the user destroy the topology if (db.serverConfig && db.serverConfig.isDestroyed()) return callback(new MongoError('topology was destroyed')); // Get the error options const commandOptions = { writeCommand: true }; if (options['dbName']) commandOptions.dbName = options['dbName']; // Get additional values const maxTimeMS = typeof options.maxTimeMS === 'number' ? options.maxTimeMS : null; // Add maxTimeMS to options if set if (maxTimeMS != null) commandOptions.maxTimeMS = maxTimeMS; // Build the command to execute let command = { dropUser: username }; // Apply write concern to command command = applyWriteConcern(command, { db }, options); // Force write using primary commandOptions.readPreference = ReadPreference.primary; // Execute the command executeCommand(db, command, commandOptions, (err, result) => { if (err && !err.ok && err.code === undefined) return handleCallback(callback, { code: -5000 }); if (err) return handleCallback(callback, err, null); handleCallback(callback, null, result.ok ? true : false); }); }
javascript
function executeAuthRemoveUserCommand(db, username, options, callback) { if (typeof options === 'function') (callback = options), (options = {}); options = options || {}; // Did the user destroy the topology if (db.serverConfig && db.serverConfig.isDestroyed()) return callback(new MongoError('topology was destroyed')); // Get the error options const commandOptions = { writeCommand: true }; if (options['dbName']) commandOptions.dbName = options['dbName']; // Get additional values const maxTimeMS = typeof options.maxTimeMS === 'number' ? options.maxTimeMS : null; // Add maxTimeMS to options if set if (maxTimeMS != null) commandOptions.maxTimeMS = maxTimeMS; // Build the command to execute let command = { dropUser: username }; // Apply write concern to command command = applyWriteConcern(command, { db }, options); // Force write using primary commandOptions.readPreference = ReadPreference.primary; // Execute the command executeCommand(db, command, commandOptions, (err, result) => { if (err && !err.ok && err.code === undefined) return handleCallback(callback, { code: -5000 }); if (err) return handleCallback(callback, err, null); handleCallback(callback, null, result.ok ? true : false); }); }
[ "function", "executeAuthRemoveUserCommand", "(", "db", ",", "username", ",", "options", ",", "callback", ")", "{", "if", "(", "typeof", "options", "===", "'function'", ")", "(", "callback", "=", "options", ")", ",", "(", "options", "=", "{", "}", ")", ";", "options", "=", "options", "||", "{", "}", ";", "// Did the user destroy the topology", "if", "(", "db", ".", "serverConfig", "&&", "db", ".", "serverConfig", ".", "isDestroyed", "(", ")", ")", "return", "callback", "(", "new", "MongoError", "(", "'topology was destroyed'", ")", ")", ";", "// Get the error options", "const", "commandOptions", "=", "{", "writeCommand", ":", "true", "}", ";", "if", "(", "options", "[", "'dbName'", "]", ")", "commandOptions", ".", "dbName", "=", "options", "[", "'dbName'", "]", ";", "// Get additional values", "const", "maxTimeMS", "=", "typeof", "options", ".", "maxTimeMS", "===", "'number'", "?", "options", ".", "maxTimeMS", ":", "null", ";", "// Add maxTimeMS to options if set", "if", "(", "maxTimeMS", "!=", "null", ")", "commandOptions", ".", "maxTimeMS", "=", "maxTimeMS", ";", "// Build the command to execute", "let", "command", "=", "{", "dropUser", ":", "username", "}", ";", "// Apply write concern to command", "command", "=", "applyWriteConcern", "(", "command", ",", "{", "db", "}", ",", "options", ")", ";", "// Force write using primary", "commandOptions", ".", "readPreference", "=", "ReadPreference", ".", "primary", ";", "// Execute the command", "executeCommand", "(", "db", ",", "command", ",", "commandOptions", ",", "(", "err", ",", "result", ")", "=>", "{", "if", "(", "err", "&&", "!", "err", ".", "ok", "&&", "err", ".", "code", "===", "undefined", ")", "return", "handleCallback", "(", "callback", ",", "{", "code", ":", "-", "5000", "}", ")", ";", "if", "(", "err", ")", "return", "handleCallback", "(", "callback", ",", "err", ",", "null", ")", ";", "handleCallback", "(", "callback", ",", "null", ",", "result", ".", "ok", "?", "true", ":", "false", ")", ";", "}", ")", ";", "}" ]
Run the dropUser command. @param {Db} db The Db instance on which to execute the command. @param {string} username The username of the user to remove. @param {object} [options] Optional settings. See Db.prototype.removeUser for a list of options. @param {Db~resultCallback} [callback] The command result callback
[ "Run", "the", "dropUser", "command", "." ]
0afbbccf1bd7d437610c33cbd5523f01bc6bc6e5
https://github.com/mongodb/node-mongodb-native/blob/0afbbccf1bd7d437610c33cbd5523f01bc6bc6e5/lib/operations/db_ops.js#L951-L985
6,447
mongodb/node-mongodb-native
lib/operations/collection_ops.js
checkForAtomicOperators
function checkForAtomicOperators(update) { const keys = Object.keys(update); // same errors as the server would give for update doc lacking atomic operators if (keys.length === 0) { return toError('The update operation document must contain at least one atomic operator.'); } if (keys[0][0] !== '$') { return toError('the update operation document must contain atomic operators.'); } }
javascript
function checkForAtomicOperators(update) { const keys = Object.keys(update); // same errors as the server would give for update doc lacking atomic operators if (keys.length === 0) { return toError('The update operation document must contain at least one atomic operator.'); } if (keys[0][0] !== '$') { return toError('the update operation document must contain atomic operators.'); } }
[ "function", "checkForAtomicOperators", "(", "update", ")", "{", "const", "keys", "=", "Object", ".", "keys", "(", "update", ")", ";", "// same errors as the server would give for update doc lacking atomic operators", "if", "(", "keys", ".", "length", "===", "0", ")", "{", "return", "toError", "(", "'The update operation document must contain at least one atomic operator.'", ")", ";", "}", "if", "(", "keys", "[", "0", "]", "[", "0", "]", "!==", "'$'", ")", "{", "return", "toError", "(", "'the update operation document must contain atomic operators.'", ")", ";", "}", "}" ]
Check the update operation to ensure it has atomic operators.
[ "Check", "the", "update", "operation", "to", "ensure", "it", "has", "atomic", "operators", "." ]
0afbbccf1bd7d437610c33cbd5523f01bc6bc6e5
https://github.com/mongodb/node-mongodb-native/blob/0afbbccf1bd7d437610c33cbd5523f01bc6bc6e5/lib/operations/collection_ops.js#L167-L178
6,448
mongodb/node-mongodb-native
lib/operations/collection_ops.js
count
function count(coll, query, options, callback) { if (typeof options === 'function') (callback = options), (options = {}); options = Object.assign({}, options); options.collectionName = coll.s.name; options.readPreference = resolveReadPreference(options, { db: coll.s.db, collection: coll }); let cmd; try { cmd = buildCountCommand(coll, query, options); } catch (err) { return callback(err); } executeCommand(coll.s.db, cmd, options, (err, result) => { if (err) return handleCallback(callback, err); handleCallback(callback, null, result.n); }); }
javascript
function count(coll, query, options, callback) { if (typeof options === 'function') (callback = options), (options = {}); options = Object.assign({}, options); options.collectionName = coll.s.name; options.readPreference = resolveReadPreference(options, { db: coll.s.db, collection: coll }); let cmd; try { cmd = buildCountCommand(coll, query, options); } catch (err) { return callback(err); } executeCommand(coll.s.db, cmd, options, (err, result) => { if (err) return handleCallback(callback, err); handleCallback(callback, null, result.n); }); }
[ "function", "count", "(", "coll", ",", "query", ",", "options", ",", "callback", ")", "{", "if", "(", "typeof", "options", "===", "'function'", ")", "(", "callback", "=", "options", ")", ",", "(", "options", "=", "{", "}", ")", ";", "options", "=", "Object", ".", "assign", "(", "{", "}", ",", "options", ")", ";", "options", ".", "collectionName", "=", "coll", ".", "s", ".", "name", ";", "options", ".", "readPreference", "=", "resolveReadPreference", "(", "options", ",", "{", "db", ":", "coll", ".", "s", ".", "db", ",", "collection", ":", "coll", "}", ")", ";", "let", "cmd", ";", "try", "{", "cmd", "=", "buildCountCommand", "(", "coll", ",", "query", ",", "options", ")", ";", "}", "catch", "(", "err", ")", "{", "return", "callback", "(", "err", ")", ";", "}", "executeCommand", "(", "coll", ".", "s", ".", "db", ",", "cmd", ",", "options", ",", "(", "err", ",", "result", ")", "=>", "{", "if", "(", "err", ")", "return", "handleCallback", "(", "callback", ",", "err", ")", ";", "handleCallback", "(", "callback", ",", "null", ",", "result", ".", "n", ")", ";", "}", ")", ";", "}" ]
Count the number of documents in the collection that match the query. @method @param {Collection} a Collection instance. @param {object} query The query for the count. @param {object} [options] Optional settings. See Collection.prototype.count for a list of options. @param {Collection~countCallback} [callback] The command result callback
[ "Count", "the", "number", "of", "documents", "in", "the", "collection", "that", "match", "the", "query", "." ]
0afbbccf1bd7d437610c33cbd5523f01bc6bc6e5
https://github.com/mongodb/node-mongodb-native/blob/0afbbccf1bd7d437610c33cbd5523f01bc6bc6e5/lib/operations/collection_ops.js#L189-L210
6,449
mongodb/node-mongodb-native
lib/operations/collection_ops.js
buildCountCommand
function buildCountCommand(collectionOrCursor, query, options) { const skip = options.skip; const limit = options.limit; let hint = options.hint; const maxTimeMS = options.maxTimeMS; query = query || {}; // Final query const cmd = { count: options.collectionName, query: query }; // check if collectionOrCursor is a cursor by using cursor.s.numberOfRetries if (collectionOrCursor.s.numberOfRetries) { if (collectionOrCursor.s.options.hint) { hint = collectionOrCursor.s.options.hint; } else if (collectionOrCursor.s.cmd.hint) { hint = collectionOrCursor.s.cmd.hint; } decorateWithCollation(cmd, collectionOrCursor, collectionOrCursor.s.cmd); } else { decorateWithCollation(cmd, collectionOrCursor, options); } // Add limit, skip and maxTimeMS if defined if (typeof skip === 'number') cmd.skip = skip; if (typeof limit === 'number') cmd.limit = limit; if (typeof maxTimeMS === 'number') cmd.maxTimeMS = maxTimeMS; if (hint) cmd.hint = hint; // Do we have a readConcern specified decorateWithReadConcern(cmd, collectionOrCursor); return cmd; }
javascript
function buildCountCommand(collectionOrCursor, query, options) { const skip = options.skip; const limit = options.limit; let hint = options.hint; const maxTimeMS = options.maxTimeMS; query = query || {}; // Final query const cmd = { count: options.collectionName, query: query }; // check if collectionOrCursor is a cursor by using cursor.s.numberOfRetries if (collectionOrCursor.s.numberOfRetries) { if (collectionOrCursor.s.options.hint) { hint = collectionOrCursor.s.options.hint; } else if (collectionOrCursor.s.cmd.hint) { hint = collectionOrCursor.s.cmd.hint; } decorateWithCollation(cmd, collectionOrCursor, collectionOrCursor.s.cmd); } else { decorateWithCollation(cmd, collectionOrCursor, options); } // Add limit, skip and maxTimeMS if defined if (typeof skip === 'number') cmd.skip = skip; if (typeof limit === 'number') cmd.limit = limit; if (typeof maxTimeMS === 'number') cmd.maxTimeMS = maxTimeMS; if (hint) cmd.hint = hint; // Do we have a readConcern specified decorateWithReadConcern(cmd, collectionOrCursor); return cmd; }
[ "function", "buildCountCommand", "(", "collectionOrCursor", ",", "query", ",", "options", ")", "{", "const", "skip", "=", "options", ".", "skip", ";", "const", "limit", "=", "options", ".", "limit", ";", "let", "hint", "=", "options", ".", "hint", ";", "const", "maxTimeMS", "=", "options", ".", "maxTimeMS", ";", "query", "=", "query", "||", "{", "}", ";", "// Final query", "const", "cmd", "=", "{", "count", ":", "options", ".", "collectionName", ",", "query", ":", "query", "}", ";", "// check if collectionOrCursor is a cursor by using cursor.s.numberOfRetries", "if", "(", "collectionOrCursor", ".", "s", ".", "numberOfRetries", ")", "{", "if", "(", "collectionOrCursor", ".", "s", ".", "options", ".", "hint", ")", "{", "hint", "=", "collectionOrCursor", ".", "s", ".", "options", ".", "hint", ";", "}", "else", "if", "(", "collectionOrCursor", ".", "s", ".", "cmd", ".", "hint", ")", "{", "hint", "=", "collectionOrCursor", ".", "s", ".", "cmd", ".", "hint", ";", "}", "decorateWithCollation", "(", "cmd", ",", "collectionOrCursor", ",", "collectionOrCursor", ".", "s", ".", "cmd", ")", ";", "}", "else", "{", "decorateWithCollation", "(", "cmd", ",", "collectionOrCursor", ",", "options", ")", ";", "}", "// Add limit, skip and maxTimeMS if defined", "if", "(", "typeof", "skip", "===", "'number'", ")", "cmd", ".", "skip", "=", "skip", ";", "if", "(", "typeof", "limit", "===", "'number'", ")", "cmd", ".", "limit", "=", "limit", ";", "if", "(", "typeof", "maxTimeMS", "===", "'number'", ")", "cmd", ".", "maxTimeMS", "=", "maxTimeMS", ";", "if", "(", "hint", ")", "cmd", ".", "hint", "=", "hint", ";", "// Do we have a readConcern specified", "decorateWithReadConcern", "(", "cmd", ",", "collectionOrCursor", ")", ";", "return", "cmd", ";", "}" ]
Build the count command. @method @param {collectionOrCursor} an instance of a collection or cursor @param {object} query The query for the count. @param {object} [options] Optional settings. See Collection.prototype.count and Cursor.prototype.count for a list of options.
[ "Build", "the", "count", "command", "." ]
0afbbccf1bd7d437610c33cbd5523f01bc6bc6e5
https://github.com/mongodb/node-mongodb-native/blob/0afbbccf1bd7d437610c33cbd5523f01bc6bc6e5/lib/operations/collection_ops.js#L247-L282
6,450
mongodb/node-mongodb-native
lib/operations/collection_ops.js
createIndex
function createIndex(coll, fieldOrSpec, options, callback) { createIndexDb(coll.s.db, coll.s.name, fieldOrSpec, options, callback); }
javascript
function createIndex(coll, fieldOrSpec, options, callback) { createIndexDb(coll.s.db, coll.s.name, fieldOrSpec, options, callback); }
[ "function", "createIndex", "(", "coll", ",", "fieldOrSpec", ",", "options", ",", "callback", ")", "{", "createIndexDb", "(", "coll", ".", "s", ".", "db", ",", "coll", ".", "s", ".", "name", ",", "fieldOrSpec", ",", "options", ",", "callback", ")", ";", "}" ]
Create an index on the db and collection. @method @param {Collection} a Collection instance. @param {(string|object)} fieldOrSpec Defines the index. @param {object} [options] Optional settings. See Collection.prototype.createIndex for a list of options. @param {Collection~resultCallback} [callback] The command result callback
[ "Create", "an", "index", "on", "the", "db", "and", "collection", "." ]
0afbbccf1bd7d437610c33cbd5523f01bc6bc6e5
https://github.com/mongodb/node-mongodb-native/blob/0afbbccf1bd7d437610c33cbd5523f01bc6bc6e5/lib/operations/collection_ops.js#L293-L295
6,451
mongodb/node-mongodb-native
lib/operations/collection_ops.js
deleteMany
function deleteMany(coll, filter, options, callback) { options.single = false; removeDocuments(coll, filter, options, (err, r) => deleteCallback(err, r, callback)); }
javascript
function deleteMany(coll, filter, options, callback) { options.single = false; removeDocuments(coll, filter, options, (err, r) => deleteCallback(err, r, callback)); }
[ "function", "deleteMany", "(", "coll", ",", "filter", ",", "options", ",", "callback", ")", "{", "options", ".", "single", "=", "false", ";", "removeDocuments", "(", "coll", ",", "filter", ",", "options", ",", "(", "err", ",", "r", ")", "=>", "deleteCallback", "(", "err", ",", "r", ",", "callback", ")", ")", ";", "}" ]
Delete multiple documents from the collection. @method @param {Collection} a Collection instance. @param {object} filter The Filter used to select the documents to remove @param {object} [options] Optional settings. See Collection.prototype.deleteMany for a list of options. @param {Collection~deleteWriteOpCallback} [callback] The command result callback
[ "Delete", "multiple", "documents", "from", "the", "collection", "." ]
0afbbccf1bd7d437610c33cbd5523f01bc6bc6e5
https://github.com/mongodb/node-mongodb-native/blob/0afbbccf1bd7d437610c33cbd5523f01bc6bc6e5/lib/operations/collection_ops.js#L361-L365
6,452
mongodb/node-mongodb-native
lib/operations/collection_ops.js
deleteOne
function deleteOne(coll, filter, options, callback) { options.single = true; removeDocuments(coll, filter, options, (err, r) => deleteCallback(err, r, callback)); }
javascript
function deleteOne(coll, filter, options, callback) { options.single = true; removeDocuments(coll, filter, options, (err, r) => deleteCallback(err, r, callback)); }
[ "function", "deleteOne", "(", "coll", ",", "filter", ",", "options", ",", "callback", ")", "{", "options", ".", "single", "=", "true", ";", "removeDocuments", "(", "coll", ",", "filter", ",", "options", ",", "(", "err", ",", "r", ")", "=>", "deleteCallback", "(", "err", ",", "r", ",", "callback", ")", ")", ";", "}" ]
Delete a single document from the collection. @method @param {Collection} a Collection instance. @param {object} filter The Filter used to select the document to remove @param {object} [options] Optional settings. See Collection.prototype.deleteOne for a list of options. @param {Collection~deleteWriteOpCallback} [callback] The command result callback
[ "Delete", "a", "single", "document", "from", "the", "collection", "." ]
0afbbccf1bd7d437610c33cbd5523f01bc6bc6e5
https://github.com/mongodb/node-mongodb-native/blob/0afbbccf1bd7d437610c33cbd5523f01bc6bc6e5/lib/operations/collection_ops.js#L376-L379
6,453
mongodb/node-mongodb-native
lib/operations/collection_ops.js
distinct
function distinct(coll, key, query, options, callback) { // maxTimeMS option const maxTimeMS = options.maxTimeMS; // Distinct command const cmd = { distinct: coll.s.name, key: key, query: query }; options = Object.assign({}, options); // Ensure we have the right read preference inheritance options.readPreference = resolveReadPreference(options, { db: coll.s.db, collection: coll }); // Add maxTimeMS if defined if (typeof maxTimeMS === 'number') cmd.maxTimeMS = maxTimeMS; // Do we have a readConcern specified decorateWithReadConcern(cmd, coll, options); // Have we specified collation try { decorateWithCollation(cmd, coll, options); } catch (err) { return callback(err, null); } // Execute the command executeCommand(coll.s.db, cmd, options, (err, result) => { if (err) return handleCallback(callback, err); handleCallback(callback, null, result.values); }); }
javascript
function distinct(coll, key, query, options, callback) { // maxTimeMS option const maxTimeMS = options.maxTimeMS; // Distinct command const cmd = { distinct: coll.s.name, key: key, query: query }; options = Object.assign({}, options); // Ensure we have the right read preference inheritance options.readPreference = resolveReadPreference(options, { db: coll.s.db, collection: coll }); // Add maxTimeMS if defined if (typeof maxTimeMS === 'number') cmd.maxTimeMS = maxTimeMS; // Do we have a readConcern specified decorateWithReadConcern(cmd, coll, options); // Have we specified collation try { decorateWithCollation(cmd, coll, options); } catch (err) { return callback(err, null); } // Execute the command executeCommand(coll.s.db, cmd, options, (err, result) => { if (err) return handleCallback(callback, err); handleCallback(callback, null, result.values); }); }
[ "function", "distinct", "(", "coll", ",", "key", ",", "query", ",", "options", ",", "callback", ")", "{", "// maxTimeMS option", "const", "maxTimeMS", "=", "options", ".", "maxTimeMS", ";", "// Distinct command", "const", "cmd", "=", "{", "distinct", ":", "coll", ".", "s", ".", "name", ",", "key", ":", "key", ",", "query", ":", "query", "}", ";", "options", "=", "Object", ".", "assign", "(", "{", "}", ",", "options", ")", ";", "// Ensure we have the right read preference inheritance", "options", ".", "readPreference", "=", "resolveReadPreference", "(", "options", ",", "{", "db", ":", "coll", ".", "s", ".", "db", ",", "collection", ":", "coll", "}", ")", ";", "// Add maxTimeMS if defined", "if", "(", "typeof", "maxTimeMS", "===", "'number'", ")", "cmd", ".", "maxTimeMS", "=", "maxTimeMS", ";", "// Do we have a readConcern specified", "decorateWithReadConcern", "(", "cmd", ",", "coll", ",", "options", ")", ";", "// Have we specified collation", "try", "{", "decorateWithCollation", "(", "cmd", ",", "coll", ",", "options", ")", ";", "}", "catch", "(", "err", ")", "{", "return", "callback", "(", "err", ",", "null", ")", ";", "}", "// Execute the command", "executeCommand", "(", "coll", ".", "s", ".", "db", ",", "cmd", ",", "options", ",", "(", "err", ",", "result", ")", "=>", "{", "if", "(", "err", ")", "return", "handleCallback", "(", "callback", ",", "err", ")", ";", "handleCallback", "(", "callback", ",", "null", ",", "result", ".", "values", ")", ";", "}", ")", ";", "}" ]
Return a list of distinct values for the given key across a collection. @method @param {Collection} a Collection instance. @param {string} key Field of the document to find distinct values for. @param {object} query The query for filtering the set of documents to which we apply the distinct filter. @param {object} [options] Optional settings. See Collection.prototype.distinct for a list of options. @param {Collection~resultCallback} [callback] The command result callback
[ "Return", "a", "list", "of", "distinct", "values", "for", "the", "given", "key", "across", "a", "collection", "." ]
0afbbccf1bd7d437610c33cbd5523f01bc6bc6e5
https://github.com/mongodb/node-mongodb-native/blob/0afbbccf1bd7d437610c33cbd5523f01bc6bc6e5/lib/operations/collection_ops.js#L391-L424
6,454
mongodb/node-mongodb-native
lib/operations/collection_ops.js
dropIndex
function dropIndex(coll, indexName, options, callback) { // Delete index command const cmd = { dropIndexes: coll.s.name, index: indexName }; // Decorate command with writeConcern if supported applyWriteConcern(cmd, { db: coll.s.db, collection: coll }, options); // Execute command executeCommand(coll.s.db, cmd, options, (err, result) => { if (typeof callback !== 'function') return; if (err) return handleCallback(callback, err, null); handleCallback(callback, null, result); }); }
javascript
function dropIndex(coll, indexName, options, callback) { // Delete index command const cmd = { dropIndexes: coll.s.name, index: indexName }; // Decorate command with writeConcern if supported applyWriteConcern(cmd, { db: coll.s.db, collection: coll }, options); // Execute command executeCommand(coll.s.db, cmd, options, (err, result) => { if (typeof callback !== 'function') return; if (err) return handleCallback(callback, err, null); handleCallback(callback, null, result); }); }
[ "function", "dropIndex", "(", "coll", ",", "indexName", ",", "options", ",", "callback", ")", "{", "// Delete index command", "const", "cmd", "=", "{", "dropIndexes", ":", "coll", ".", "s", ".", "name", ",", "index", ":", "indexName", "}", ";", "// Decorate command with writeConcern if supported", "applyWriteConcern", "(", "cmd", ",", "{", "db", ":", "coll", ".", "s", ".", "db", ",", "collection", ":", "coll", "}", ",", "options", ")", ";", "// Execute command", "executeCommand", "(", "coll", ".", "s", ".", "db", ",", "cmd", ",", "options", ",", "(", "err", ",", "result", ")", "=>", "{", "if", "(", "typeof", "callback", "!==", "'function'", ")", "return", ";", "if", "(", "err", ")", "return", "handleCallback", "(", "callback", ",", "err", ",", "null", ")", ";", "handleCallback", "(", "callback", ",", "null", ",", "result", ")", ";", "}", ")", ";", "}" ]
Drop an index from this collection. @method @param {Collection} a Collection instance. @param {string} indexName Name of the index to drop. @param {object} [options] Optional settings. See Collection.prototype.dropIndex for a list of options. @param {Collection~resultCallback} [callback] The command result callback
[ "Drop", "an", "index", "from", "this", "collection", "." ]
0afbbccf1bd7d437610c33cbd5523f01bc6bc6e5
https://github.com/mongodb/node-mongodb-native/blob/0afbbccf1bd7d437610c33cbd5523f01bc6bc6e5/lib/operations/collection_ops.js#L435-L448
6,455
mongodb/node-mongodb-native
lib/operations/collection_ops.js
dropIndexes
function dropIndexes(coll, options, callback) { dropIndex(coll, '*', options, err => { if (err) return handleCallback(callback, err, false); handleCallback(callback, null, true); }); }
javascript
function dropIndexes(coll, options, callback) { dropIndex(coll, '*', options, err => { if (err) return handleCallback(callback, err, false); handleCallback(callback, null, true); }); }
[ "function", "dropIndexes", "(", "coll", ",", "options", ",", "callback", ")", "{", "dropIndex", "(", "coll", ",", "'*'", ",", "options", ",", "err", "=>", "{", "if", "(", "err", ")", "return", "handleCallback", "(", "callback", ",", "err", ",", "false", ")", ";", "handleCallback", "(", "callback", ",", "null", ",", "true", ")", ";", "}", ")", ";", "}" ]
Drop all indexes from this collection. @method @param {Collection} a Collection instance. @param {Object} [options] Optional settings. See Collection.prototype.dropIndexes for a list of options. @param {Collection~resultCallback} [callback] The command result callback
[ "Drop", "all", "indexes", "from", "this", "collection", "." ]
0afbbccf1bd7d437610c33cbd5523f01bc6bc6e5
https://github.com/mongodb/node-mongodb-native/blob/0afbbccf1bd7d437610c33cbd5523f01bc6bc6e5/lib/operations/collection_ops.js#L458-L463
6,456
mongodb/node-mongodb-native
lib/operations/collection_ops.js
ensureIndex
function ensureIndex(coll, fieldOrSpec, options, callback) { ensureIndexDb(coll.s.db, coll.s.name, fieldOrSpec, options, callback); }
javascript
function ensureIndex(coll, fieldOrSpec, options, callback) { ensureIndexDb(coll.s.db, coll.s.name, fieldOrSpec, options, callback); }
[ "function", "ensureIndex", "(", "coll", ",", "fieldOrSpec", ",", "options", ",", "callback", ")", "{", "ensureIndexDb", "(", "coll", ".", "s", ".", "db", ",", "coll", ".", "s", ".", "name", ",", "fieldOrSpec", ",", "options", ",", "callback", ")", ";", "}" ]
Ensure that an index exists. If the index does not exist, this function creates it. @method @param {Collection} a Collection instance. @param {(string|object)} fieldOrSpec Defines the index. @param {object} [options] Optional settings. See Collection.prototype.ensureIndex for a list of options. @param {Collection~resultCallback} [callback] The command result callback
[ "Ensure", "that", "an", "index", "exists", ".", "If", "the", "index", "does", "not", "exist", "this", "function", "creates", "it", "." ]
0afbbccf1bd7d437610c33cbd5523f01bc6bc6e5
https://github.com/mongodb/node-mongodb-native/blob/0afbbccf1bd7d437610c33cbd5523f01bc6bc6e5/lib/operations/collection_ops.js#L474-L476
6,457
mongodb/node-mongodb-native
lib/operations/collection_ops.js
findAndModify
function findAndModify(coll, query, sort, doc, options, callback) { // Create findAndModify command object const queryObject = { findAndModify: coll.s.name, query: query }; sort = formattedOrderClause(sort); if (sort) { queryObject.sort = sort; } queryObject.new = options.new ? true : false; queryObject.remove = options.remove ? true : false; queryObject.upsert = options.upsert ? true : false; const projection = options.projection || options.fields; if (projection) { queryObject.fields = projection; } if (options.arrayFilters) { queryObject.arrayFilters = options.arrayFilters; delete options.arrayFilters; } if (doc && !options.remove) { queryObject.update = doc; } if (options.maxTimeMS) queryObject.maxTimeMS = options.maxTimeMS; // Either use override on the function, or go back to default on either the collection // level or db options.serializeFunctions = options.serializeFunctions || coll.s.serializeFunctions; // No check on the documents options.checkKeys = false; // Final options for retryable writes and write concern let finalOptions = Object.assign({}, options); finalOptions = applyRetryableWrites(finalOptions, coll.s.db); finalOptions = applyWriteConcern(finalOptions, { db: coll.s.db, collection: coll }, options); // Decorate the findAndModify command with the write Concern if (finalOptions.writeConcern) { queryObject.writeConcern = finalOptions.writeConcern; } // Have we specified bypassDocumentValidation if (finalOptions.bypassDocumentValidation === true) { queryObject.bypassDocumentValidation = finalOptions.bypassDocumentValidation; } finalOptions.readPreference = ReadPreference.primary; // Have we specified collation try { decorateWithCollation(queryObject, coll, finalOptions); } catch (err) { return callback(err, null); } // Execute the command executeCommand(coll.s.db, queryObject, finalOptions, (err, result) => { if (err) return handleCallback(callback, err, null); return handleCallback(callback, null, result); }); }
javascript
function findAndModify(coll, query, sort, doc, options, callback) { // Create findAndModify command object const queryObject = { findAndModify: coll.s.name, query: query }; sort = formattedOrderClause(sort); if (sort) { queryObject.sort = sort; } queryObject.new = options.new ? true : false; queryObject.remove = options.remove ? true : false; queryObject.upsert = options.upsert ? true : false; const projection = options.projection || options.fields; if (projection) { queryObject.fields = projection; } if (options.arrayFilters) { queryObject.arrayFilters = options.arrayFilters; delete options.arrayFilters; } if (doc && !options.remove) { queryObject.update = doc; } if (options.maxTimeMS) queryObject.maxTimeMS = options.maxTimeMS; // Either use override on the function, or go back to default on either the collection // level or db options.serializeFunctions = options.serializeFunctions || coll.s.serializeFunctions; // No check on the documents options.checkKeys = false; // Final options for retryable writes and write concern let finalOptions = Object.assign({}, options); finalOptions = applyRetryableWrites(finalOptions, coll.s.db); finalOptions = applyWriteConcern(finalOptions, { db: coll.s.db, collection: coll }, options); // Decorate the findAndModify command with the write Concern if (finalOptions.writeConcern) { queryObject.writeConcern = finalOptions.writeConcern; } // Have we specified bypassDocumentValidation if (finalOptions.bypassDocumentValidation === true) { queryObject.bypassDocumentValidation = finalOptions.bypassDocumentValidation; } finalOptions.readPreference = ReadPreference.primary; // Have we specified collation try { decorateWithCollation(queryObject, coll, finalOptions); } catch (err) { return callback(err, null); } // Execute the command executeCommand(coll.s.db, queryObject, finalOptions, (err, result) => { if (err) return handleCallback(callback, err, null); return handleCallback(callback, null, result); }); }
[ "function", "findAndModify", "(", "coll", ",", "query", ",", "sort", ",", "doc", ",", "options", ",", "callback", ")", "{", "// Create findAndModify command object", "const", "queryObject", "=", "{", "findAndModify", ":", "coll", ".", "s", ".", "name", ",", "query", ":", "query", "}", ";", "sort", "=", "formattedOrderClause", "(", "sort", ")", ";", "if", "(", "sort", ")", "{", "queryObject", ".", "sort", "=", "sort", ";", "}", "queryObject", ".", "new", "=", "options", ".", "new", "?", "true", ":", "false", ";", "queryObject", ".", "remove", "=", "options", ".", "remove", "?", "true", ":", "false", ";", "queryObject", ".", "upsert", "=", "options", ".", "upsert", "?", "true", ":", "false", ";", "const", "projection", "=", "options", ".", "projection", "||", "options", ".", "fields", ";", "if", "(", "projection", ")", "{", "queryObject", ".", "fields", "=", "projection", ";", "}", "if", "(", "options", ".", "arrayFilters", ")", "{", "queryObject", ".", "arrayFilters", "=", "options", ".", "arrayFilters", ";", "delete", "options", ".", "arrayFilters", ";", "}", "if", "(", "doc", "&&", "!", "options", ".", "remove", ")", "{", "queryObject", ".", "update", "=", "doc", ";", "}", "if", "(", "options", ".", "maxTimeMS", ")", "queryObject", ".", "maxTimeMS", "=", "options", ".", "maxTimeMS", ";", "// Either use override on the function, or go back to default on either the collection", "// level or db", "options", ".", "serializeFunctions", "=", "options", ".", "serializeFunctions", "||", "coll", ".", "s", ".", "serializeFunctions", ";", "// No check on the documents", "options", ".", "checkKeys", "=", "false", ";", "// Final options for retryable writes and write concern", "let", "finalOptions", "=", "Object", ".", "assign", "(", "{", "}", ",", "options", ")", ";", "finalOptions", "=", "applyRetryableWrites", "(", "finalOptions", ",", "coll", ".", "s", ".", "db", ")", ";", "finalOptions", "=", "applyWriteConcern", "(", "finalOptions", ",", "{", "db", ":", "coll", ".", "s", ".", "db", ",", "collection", ":", "coll", "}", ",", "options", ")", ";", "// Decorate the findAndModify command with the write Concern", "if", "(", "finalOptions", ".", "writeConcern", ")", "{", "queryObject", ".", "writeConcern", "=", "finalOptions", ".", "writeConcern", ";", "}", "// Have we specified bypassDocumentValidation", "if", "(", "finalOptions", ".", "bypassDocumentValidation", "===", "true", ")", "{", "queryObject", ".", "bypassDocumentValidation", "=", "finalOptions", ".", "bypassDocumentValidation", ";", "}", "finalOptions", ".", "readPreference", "=", "ReadPreference", ".", "primary", ";", "// Have we specified collation", "try", "{", "decorateWithCollation", "(", "queryObject", ",", "coll", ",", "finalOptions", ")", ";", "}", "catch", "(", "err", ")", "{", "return", "callback", "(", "err", ",", "null", ")", ";", "}", "// Execute the command", "executeCommand", "(", "coll", ".", "s", ".", "db", ",", "queryObject", ",", "finalOptions", ",", "(", "err", ",", "result", ")", "=>", "{", "if", "(", "err", ")", "return", "handleCallback", "(", "callback", ",", "err", ",", "null", ")", ";", "return", "handleCallback", "(", "callback", ",", "null", ",", "result", ")", ";", "}", ")", ";", "}" ]
Find and update a document. @method @param {Collection} a Collection instance. @param {object} query Query object to locate the object to modify. @param {array} sort If multiple docs match, choose the first one in the specified sort order as the object to manipulate. @param {object} doc The fields/vals to be updated. @param {object} [options] Optional settings. See Collection.prototype.findAndModify for a list of options. @param {Collection~findAndModifyCallback} [callback] The command result callback @deprecated use findOneAndUpdate, findOneAndReplace or findOneAndDelete instead
[ "Find", "and", "update", "a", "document", "." ]
0afbbccf1bd7d437610c33cbd5523f01bc6bc6e5
https://github.com/mongodb/node-mongodb-native/blob/0afbbccf1bd7d437610c33cbd5523f01bc6bc6e5/lib/operations/collection_ops.js#L490-L560
6,458
mongodb/node-mongodb-native
lib/operations/collection_ops.js
findAndRemove
function findAndRemove(coll, query, sort, options, callback) { // Add the remove option options.remove = true; // Execute the callback findAndModify(coll, query, sort, null, options, callback); }
javascript
function findAndRemove(coll, query, sort, options, callback) { // Add the remove option options.remove = true; // Execute the callback findAndModify(coll, query, sort, null, options, callback); }
[ "function", "findAndRemove", "(", "coll", ",", "query", ",", "sort", ",", "options", ",", "callback", ")", "{", "// Add the remove option", "options", ".", "remove", "=", "true", ";", "// Execute the callback", "findAndModify", "(", "coll", ",", "query", ",", "sort", ",", "null", ",", "options", ",", "callback", ")", ";", "}" ]
Find and remove a document. @method @param {Collection} a Collection instance. @param {object} query Query object to locate the object to modify. @param {array} sort If multiple docs match, choose the first one in the specified sort order as the object to manipulate. @param {object} [options] Optional settings. See Collection.prototype.findAndRemove for a list of options. @param {Collection~resultCallback} [callback] The command result callback @deprecated use findOneAndDelete instead
[ "Find", "and", "remove", "a", "document", "." ]
0afbbccf1bd7d437610c33cbd5523f01bc6bc6e5
https://github.com/mongodb/node-mongodb-native/blob/0afbbccf1bd7d437610c33cbd5523f01bc6bc6e5/lib/operations/collection_ops.js#L573-L578
6,459
mongodb/node-mongodb-native
lib/operations/collection_ops.js
findOne
function findOne(coll, query, options, callback) { const cursor = coll .find(query, options) .limit(-1) .batchSize(1); // Return the item cursor.next((err, item) => { if (err != null) return handleCallback(callback, toError(err), null); handleCallback(callback, null, item); }); }
javascript
function findOne(coll, query, options, callback) { const cursor = coll .find(query, options) .limit(-1) .batchSize(1); // Return the item cursor.next((err, item) => { if (err != null) return handleCallback(callback, toError(err), null); handleCallback(callback, null, item); }); }
[ "function", "findOne", "(", "coll", ",", "query", ",", "options", ",", "callback", ")", "{", "const", "cursor", "=", "coll", ".", "find", "(", "query", ",", "options", ")", ".", "limit", "(", "-", "1", ")", ".", "batchSize", "(", "1", ")", ";", "// Return the item", "cursor", ".", "next", "(", "(", "err", ",", "item", ")", "=>", "{", "if", "(", "err", "!=", "null", ")", "return", "handleCallback", "(", "callback", ",", "toError", "(", "err", ")", ",", "null", ")", ";", "handleCallback", "(", "callback", ",", "null", ",", "item", ")", ";", "}", ")", ";", "}" ]
Fetch the first document that matches the query. @method @param {Collection} a Collection instance. @param {object} query Query for find Operation @param {object} [options] Optional settings. See Collection.prototype.findOne for a list of options. @param {Collection~resultCallback} [callback] The command result callback
[ "Fetch", "the", "first", "document", "that", "matches", "the", "query", "." ]
0afbbccf1bd7d437610c33cbd5523f01bc6bc6e5
https://github.com/mongodb/node-mongodb-native/blob/0afbbccf1bd7d437610c33cbd5523f01bc6bc6e5/lib/operations/collection_ops.js#L589-L600
6,460
mongodb/node-mongodb-native
lib/operations/collection_ops.js
findOneAndDelete
function findOneAndDelete(coll, filter, options, callback) { // Final options const finalOptions = Object.assign({}, options); finalOptions.fields = options.projection; finalOptions.remove = true; // Execute find and Modify findAndModify(coll, filter, options.sort, null, finalOptions, callback); }
javascript
function findOneAndDelete(coll, filter, options, callback) { // Final options const finalOptions = Object.assign({}, options); finalOptions.fields = options.projection; finalOptions.remove = true; // Execute find and Modify findAndModify(coll, filter, options.sort, null, finalOptions, callback); }
[ "function", "findOneAndDelete", "(", "coll", ",", "filter", ",", "options", ",", "callback", ")", "{", "// Final options", "const", "finalOptions", "=", "Object", ".", "assign", "(", "{", "}", ",", "options", ")", ";", "finalOptions", ".", "fields", "=", "options", ".", "projection", ";", "finalOptions", ".", "remove", "=", "true", ";", "// Execute find and Modify", "findAndModify", "(", "coll", ",", "filter", ",", "options", ".", "sort", ",", "null", ",", "finalOptions", ",", "callback", ")", ";", "}" ]
Find a document and delete it in one atomic operation. This requires a write lock for the duration of the operation. @method @param {Collection} a Collection instance. @param {object} filter Document selection filter. @param {object} [options] Optional settings. See Collection.prototype.findOneAndDelete for a list of options. @param {Collection~findAndModifyCallback} [callback] The collection result callback
[ "Find", "a", "document", "and", "delete", "it", "in", "one", "atomic", "operation", ".", "This", "requires", "a", "write", "lock", "for", "the", "duration", "of", "the", "operation", "." ]
0afbbccf1bd7d437610c33cbd5523f01bc6bc6e5
https://github.com/mongodb/node-mongodb-native/blob/0afbbccf1bd7d437610c33cbd5523f01bc6bc6e5/lib/operations/collection_ops.js#L611-L618
6,461
mongodb/node-mongodb-native
lib/operations/collection_ops.js
findOneAndReplace
function findOneAndReplace(coll, filter, replacement, options, callback) { // Final options const finalOptions = Object.assign({}, options); finalOptions.fields = options.projection; finalOptions.update = true; finalOptions.new = options.returnOriginal !== void 0 ? !options.returnOriginal : false; finalOptions.upsert = options.upsert !== void 0 ? !!options.upsert : false; // Execute findAndModify findAndModify(coll, filter, options.sort, replacement, finalOptions, callback); }
javascript
function findOneAndReplace(coll, filter, replacement, options, callback) { // Final options const finalOptions = Object.assign({}, options); finalOptions.fields = options.projection; finalOptions.update = true; finalOptions.new = options.returnOriginal !== void 0 ? !options.returnOriginal : false; finalOptions.upsert = options.upsert !== void 0 ? !!options.upsert : false; // Execute findAndModify findAndModify(coll, filter, options.sort, replacement, finalOptions, callback); }
[ "function", "findOneAndReplace", "(", "coll", ",", "filter", ",", "replacement", ",", "options", ",", "callback", ")", "{", "// Final options", "const", "finalOptions", "=", "Object", ".", "assign", "(", "{", "}", ",", "options", ")", ";", "finalOptions", ".", "fields", "=", "options", ".", "projection", ";", "finalOptions", ".", "update", "=", "true", ";", "finalOptions", ".", "new", "=", "options", ".", "returnOriginal", "!==", "void", "0", "?", "!", "options", ".", "returnOriginal", ":", "false", ";", "finalOptions", ".", "upsert", "=", "options", ".", "upsert", "!==", "void", "0", "?", "!", "!", "options", ".", "upsert", ":", "false", ";", "// Execute findAndModify", "findAndModify", "(", "coll", ",", "filter", ",", "options", ".", "sort", ",", "replacement", ",", "finalOptions", ",", "callback", ")", ";", "}" ]
Find a document and replace it in one atomic operation. This requires a write lock for the duration of the operation. @method @param {Collection} a Collection instance. @param {object} filter Document selection filter. @param {object} replacement Document replacing the matching document. @param {object} [options] Optional settings. See Collection.prototype.findOneAndReplace for a list of options. @param {Collection~findAndModifyCallback} [callback] The collection result callback
[ "Find", "a", "document", "and", "replace", "it", "in", "one", "atomic", "operation", ".", "This", "requires", "a", "write", "lock", "for", "the", "duration", "of", "the", "operation", "." ]
0afbbccf1bd7d437610c33cbd5523f01bc6bc6e5
https://github.com/mongodb/node-mongodb-native/blob/0afbbccf1bd7d437610c33cbd5523f01bc6bc6e5/lib/operations/collection_ops.js#L630-L640
6,462
mongodb/node-mongodb-native
lib/operations/collection_ops.js
geoHaystackSearch
function geoHaystackSearch(coll, x, y, options, callback) { // Build command object let commandObject = { geoSearch: coll.s.name, near: [x, y] }; // Remove read preference from hash if it exists commandObject = decorateCommand(commandObject, options, ['readPreference', 'session']); options = Object.assign({}, options); // Ensure we have the right read preference inheritance options.readPreference = resolveReadPreference(options, { db: coll.s.db, collection: coll }); // Do we have a readConcern specified decorateWithReadConcern(commandObject, coll, options); // Execute the command executeCommand(coll.s.db, commandObject, options, (err, res) => { if (err) return handleCallback(callback, err); if (res.err || res.errmsg) handleCallback(callback, toError(res)); // should we only be returning res.results here? Not sure if the user // should see the other return information handleCallback(callback, null, res); }); }
javascript
function geoHaystackSearch(coll, x, y, options, callback) { // Build command object let commandObject = { geoSearch: coll.s.name, near: [x, y] }; // Remove read preference from hash if it exists commandObject = decorateCommand(commandObject, options, ['readPreference', 'session']); options = Object.assign({}, options); // Ensure we have the right read preference inheritance options.readPreference = resolveReadPreference(options, { db: coll.s.db, collection: coll }); // Do we have a readConcern specified decorateWithReadConcern(commandObject, coll, options); // Execute the command executeCommand(coll.s.db, commandObject, options, (err, res) => { if (err) return handleCallback(callback, err); if (res.err || res.errmsg) handleCallback(callback, toError(res)); // should we only be returning res.results here? Not sure if the user // should see the other return information handleCallback(callback, null, res); }); }
[ "function", "geoHaystackSearch", "(", "coll", ",", "x", ",", "y", ",", "options", ",", "callback", ")", "{", "// Build command object", "let", "commandObject", "=", "{", "geoSearch", ":", "coll", ".", "s", ".", "name", ",", "near", ":", "[", "x", ",", "y", "]", "}", ";", "// Remove read preference from hash if it exists", "commandObject", "=", "decorateCommand", "(", "commandObject", ",", "options", ",", "[", "'readPreference'", ",", "'session'", "]", ")", ";", "options", "=", "Object", ".", "assign", "(", "{", "}", ",", "options", ")", ";", "// Ensure we have the right read preference inheritance", "options", ".", "readPreference", "=", "resolveReadPreference", "(", "options", ",", "{", "db", ":", "coll", ".", "s", ".", "db", ",", "collection", ":", "coll", "}", ")", ";", "// Do we have a readConcern specified", "decorateWithReadConcern", "(", "commandObject", ",", "coll", ",", "options", ")", ";", "// Execute the command", "executeCommand", "(", "coll", ".", "s", ".", "db", ",", "commandObject", ",", "options", ",", "(", "err", ",", "res", ")", "=>", "{", "if", "(", "err", ")", "return", "handleCallback", "(", "callback", ",", "err", ")", ";", "if", "(", "res", ".", "err", "||", "res", ".", "errmsg", ")", "handleCallback", "(", "callback", ",", "toError", "(", "res", ")", ")", ";", "// should we only be returning res.results here? Not sure if the user", "// should see the other return information", "handleCallback", "(", "callback", ",", "null", ",", "res", ")", ";", "}", ")", ";", "}" ]
Execute a geo search using a geo haystack index on a collection. @method @param {Collection} a Collection instance. @param {number} x Point to search on the x axis, ensure the indexes are ordered in the same order. @param {number} y Point to search on the y axis, ensure the indexes are ordered in the same order. @param {object} [options] Optional settings. See Collection.prototype.geoHaystackSearch for a list of options. @param {Collection~resultCallback} [callback] The command result callback
[ "Execute", "a", "geo", "search", "using", "a", "geo", "haystack", "index", "on", "a", "collection", "." ]
0afbbccf1bd7d437610c33cbd5523f01bc6bc6e5
https://github.com/mongodb/node-mongodb-native/blob/0afbbccf1bd7d437610c33cbd5523f01bc6bc6e5/lib/operations/collection_ops.js#L674-L699
6,463
mongodb/node-mongodb-native
lib/operations/collection_ops.js
group
function group(coll, keys, condition, initial, reduce, finalize, command, options, callback) { // Execute using the command if (command) { const reduceFunction = reduce && reduce._bsontype === 'Code' ? reduce : new Code(reduce); const selector = { group: { ns: coll.s.name, $reduce: reduceFunction, cond: condition, initial: initial, out: 'inline' } }; // if finalize is defined if (finalize != null) selector.group['finalize'] = finalize; // Set up group selector if ('function' === typeof keys || (keys && keys._bsontype === 'Code')) { selector.group.$keyf = keys && keys._bsontype === 'Code' ? keys : new Code(keys); } else { const hash = {}; keys.forEach(key => { hash[key] = 1; }); selector.group.key = hash; } options = Object.assign({}, options); // Ensure we have the right read preference inheritance options.readPreference = resolveReadPreference(options, { db: coll.s.db, collection: coll }); // Do we have a readConcern specified decorateWithReadConcern(selector, coll, options); // Have we specified collation try { decorateWithCollation(selector, coll, options); } catch (err) { return callback(err, null); } // Execute command executeCommand(coll.s.db, selector, options, (err, result) => { if (err) return handleCallback(callback, err, null); handleCallback(callback, null, result.retval); }); } else { // Create execution scope const scope = reduce != null && reduce._bsontype === 'Code' ? reduce.scope : {}; scope.ns = coll.s.name; scope.keys = keys; scope.condition = condition; scope.initial = initial; // Pass in the function text to execute within mongodb. const groupfn = groupFunction.replace(/ reduce;/, reduce.toString() + ';'); evaluate(coll.s.db, new Code(groupfn, scope), null, options, (err, results) => { if (err) return handleCallback(callback, err, null); handleCallback(callback, null, results.result || results); }); } }
javascript
function group(coll, keys, condition, initial, reduce, finalize, command, options, callback) { // Execute using the command if (command) { const reduceFunction = reduce && reduce._bsontype === 'Code' ? reduce : new Code(reduce); const selector = { group: { ns: coll.s.name, $reduce: reduceFunction, cond: condition, initial: initial, out: 'inline' } }; // if finalize is defined if (finalize != null) selector.group['finalize'] = finalize; // Set up group selector if ('function' === typeof keys || (keys && keys._bsontype === 'Code')) { selector.group.$keyf = keys && keys._bsontype === 'Code' ? keys : new Code(keys); } else { const hash = {}; keys.forEach(key => { hash[key] = 1; }); selector.group.key = hash; } options = Object.assign({}, options); // Ensure we have the right read preference inheritance options.readPreference = resolveReadPreference(options, { db: coll.s.db, collection: coll }); // Do we have a readConcern specified decorateWithReadConcern(selector, coll, options); // Have we specified collation try { decorateWithCollation(selector, coll, options); } catch (err) { return callback(err, null); } // Execute command executeCommand(coll.s.db, selector, options, (err, result) => { if (err) return handleCallback(callback, err, null); handleCallback(callback, null, result.retval); }); } else { // Create execution scope const scope = reduce != null && reduce._bsontype === 'Code' ? reduce.scope : {}; scope.ns = coll.s.name; scope.keys = keys; scope.condition = condition; scope.initial = initial; // Pass in the function text to execute within mongodb. const groupfn = groupFunction.replace(/ reduce;/, reduce.toString() + ';'); evaluate(coll.s.db, new Code(groupfn, scope), null, options, (err, results) => { if (err) return handleCallback(callback, err, null); handleCallback(callback, null, results.result || results); }); } }
[ "function", "group", "(", "coll", ",", "keys", ",", "condition", ",", "initial", ",", "reduce", ",", "finalize", ",", "command", ",", "options", ",", "callback", ")", "{", "// Execute using the command", "if", "(", "command", ")", "{", "const", "reduceFunction", "=", "reduce", "&&", "reduce", ".", "_bsontype", "===", "'Code'", "?", "reduce", ":", "new", "Code", "(", "reduce", ")", ";", "const", "selector", "=", "{", "group", ":", "{", "ns", ":", "coll", ".", "s", ".", "name", ",", "$reduce", ":", "reduceFunction", ",", "cond", ":", "condition", ",", "initial", ":", "initial", ",", "out", ":", "'inline'", "}", "}", ";", "// if finalize is defined", "if", "(", "finalize", "!=", "null", ")", "selector", ".", "group", "[", "'finalize'", "]", "=", "finalize", ";", "// Set up group selector", "if", "(", "'function'", "===", "typeof", "keys", "||", "(", "keys", "&&", "keys", ".", "_bsontype", "===", "'Code'", ")", ")", "{", "selector", ".", "group", ".", "$keyf", "=", "keys", "&&", "keys", ".", "_bsontype", "===", "'Code'", "?", "keys", ":", "new", "Code", "(", "keys", ")", ";", "}", "else", "{", "const", "hash", "=", "{", "}", ";", "keys", ".", "forEach", "(", "key", "=>", "{", "hash", "[", "key", "]", "=", "1", ";", "}", ")", ";", "selector", ".", "group", ".", "key", "=", "hash", ";", "}", "options", "=", "Object", ".", "assign", "(", "{", "}", ",", "options", ")", ";", "// Ensure we have the right read preference inheritance", "options", ".", "readPreference", "=", "resolveReadPreference", "(", "options", ",", "{", "db", ":", "coll", ".", "s", ".", "db", ",", "collection", ":", "coll", "}", ")", ";", "// Do we have a readConcern specified", "decorateWithReadConcern", "(", "selector", ",", "coll", ",", "options", ")", ";", "// Have we specified collation", "try", "{", "decorateWithCollation", "(", "selector", ",", "coll", ",", "options", ")", ";", "}", "catch", "(", "err", ")", "{", "return", "callback", "(", "err", ",", "null", ")", ";", "}", "// Execute command", "executeCommand", "(", "coll", ".", "s", ".", "db", ",", "selector", ",", "options", ",", "(", "err", ",", "result", ")", "=>", "{", "if", "(", "err", ")", "return", "handleCallback", "(", "callback", ",", "err", ",", "null", ")", ";", "handleCallback", "(", "callback", ",", "null", ",", "result", ".", "retval", ")", ";", "}", ")", ";", "}", "else", "{", "// Create execution scope", "const", "scope", "=", "reduce", "!=", "null", "&&", "reduce", ".", "_bsontype", "===", "'Code'", "?", "reduce", ".", "scope", ":", "{", "}", ";", "scope", ".", "ns", "=", "coll", ".", "s", ".", "name", ";", "scope", ".", "keys", "=", "keys", ";", "scope", ".", "condition", "=", "condition", ";", "scope", ".", "initial", "=", "initial", ";", "// Pass in the function text to execute within mongodb.", "const", "groupfn", "=", "groupFunction", ".", "replace", "(", "/", " reduce;", "/", ",", "reduce", ".", "toString", "(", ")", "+", "';'", ")", ";", "evaluate", "(", "coll", ".", "s", ".", "db", ",", "new", "Code", "(", "groupfn", ",", "scope", ")", ",", "null", ",", "options", ",", "(", "err", ",", "results", ")", "=>", "{", "if", "(", "err", ")", "return", "handleCallback", "(", "callback", ",", "err", ",", "null", ")", ";", "handleCallback", "(", "callback", ",", "null", ",", "results", ".", "result", "||", "results", ")", ";", "}", ")", ";", "}", "}" ]
Run a group command across a collection. @method @param {Collection} a Collection instance. @param {(object|array|function|code)} keys An object, array or function expressing the keys to group by. @param {object} condition An optional condition that must be true for a row to be considered. @param {object} initial Initial value of the aggregation counter object. @param {(function|Code)} reduce The reduce function aggregates (reduces) the objects iterated @param {(function|Code)} finalize An optional function to be run on each item in the result set just before the item is returned. @param {boolean} command Specify if you wish to run using the internal group command or using eval, default is true. @param {object} [options] Optional settings. See Collection.prototype.group for a list of options. @param {Collection~resultCallback} [callback] The command result callback @deprecated MongoDB 3.6 or higher will no longer support the group command. We recommend rewriting using the aggregation framework.
[ "Run", "a", "group", "command", "across", "a", "collection", "." ]
0afbbccf1bd7d437610c33cbd5523f01bc6bc6e5
https://github.com/mongodb/node-mongodb-native/blob/0afbbccf1bd7d437610c33cbd5523f01bc6bc6e5/lib/operations/collection_ops.js#L716-L780
6,464
mongodb/node-mongodb-native
lib/operations/collection_ops.js
indexes
function indexes(coll, options, callback) { options = Object.assign({}, { full: true }, options); indexInformationDb(coll.s.db, coll.s.name, options, callback); }
javascript
function indexes(coll, options, callback) { options = Object.assign({}, { full: true }, options); indexInformationDb(coll.s.db, coll.s.name, options, callback); }
[ "function", "indexes", "(", "coll", ",", "options", ",", "callback", ")", "{", "options", "=", "Object", ".", "assign", "(", "{", "}", ",", "{", "full", ":", "true", "}", ",", "options", ")", ";", "indexInformationDb", "(", "coll", ".", "s", ".", "db", ",", "coll", ".", "s", ".", "name", ",", "options", ",", "callback", ")", ";", "}" ]
Retrieve all the indexes on the collection. @method @param {Collection} a Collection instance. @param {Object} [options] Optional settings. See Collection.prototype.indexes for a list of options. @param {Collection~resultCallback} [callback] The command result callback
[ "Retrieve", "all", "the", "indexes", "on", "the", "collection", "." ]
0afbbccf1bd7d437610c33cbd5523f01bc6bc6e5
https://github.com/mongodb/node-mongodb-native/blob/0afbbccf1bd7d437610c33cbd5523f01bc6bc6e5/lib/operations/collection_ops.js#L790-L793
6,465
mongodb/node-mongodb-native
lib/operations/collection_ops.js
indexExists
function indexExists(coll, indexes, options, callback) { indexInformation(coll, options, (err, indexInformation) => { // If we have an error return if (err != null) return handleCallback(callback, err, null); // Let's check for the index names if (!Array.isArray(indexes)) return handleCallback(callback, null, indexInformation[indexes] != null); // Check in list of indexes for (let i = 0; i < indexes.length; i++) { if (indexInformation[indexes[i]] == null) { return handleCallback(callback, null, false); } } // All keys found return true return handleCallback(callback, null, true); }); }
javascript
function indexExists(coll, indexes, options, callback) { indexInformation(coll, options, (err, indexInformation) => { // If we have an error return if (err != null) return handleCallback(callback, err, null); // Let's check for the index names if (!Array.isArray(indexes)) return handleCallback(callback, null, indexInformation[indexes] != null); // Check in list of indexes for (let i = 0; i < indexes.length; i++) { if (indexInformation[indexes[i]] == null) { return handleCallback(callback, null, false); } } // All keys found return true return handleCallback(callback, null, true); }); }
[ "function", "indexExists", "(", "coll", ",", "indexes", ",", "options", ",", "callback", ")", "{", "indexInformation", "(", "coll", ",", "options", ",", "(", "err", ",", "indexInformation", ")", "=>", "{", "// If we have an error return", "if", "(", "err", "!=", "null", ")", "return", "handleCallback", "(", "callback", ",", "err", ",", "null", ")", ";", "// Let's check for the index names", "if", "(", "!", "Array", ".", "isArray", "(", "indexes", ")", ")", "return", "handleCallback", "(", "callback", ",", "null", ",", "indexInformation", "[", "indexes", "]", "!=", "null", ")", ";", "// Check in list of indexes", "for", "(", "let", "i", "=", "0", ";", "i", "<", "indexes", ".", "length", ";", "i", "++", ")", "{", "if", "(", "indexInformation", "[", "indexes", "[", "i", "]", "]", "==", "null", ")", "{", "return", "handleCallback", "(", "callback", ",", "null", ",", "false", ")", ";", "}", "}", "// All keys found return true", "return", "handleCallback", "(", "callback", ",", "null", ",", "true", ")", ";", "}", ")", ";", "}" ]
Check if one or more indexes exist on the collection. This fails on the first index that doesn't exist. @method @param {Collection} a Collection instance. @param {(string|array)} indexes One or more index names to check. @param {Object} [options] Optional settings. See Collection.prototype.indexExists for a list of options. @param {Collection~resultCallback} [callback] The command result callback
[ "Check", "if", "one", "or", "more", "indexes", "exist", "on", "the", "collection", ".", "This", "fails", "on", "the", "first", "index", "that", "doesn", "t", "exist", "." ]
0afbbccf1bd7d437610c33cbd5523f01bc6bc6e5
https://github.com/mongodb/node-mongodb-native/blob/0afbbccf1bd7d437610c33cbd5523f01bc6bc6e5/lib/operations/collection_ops.js#L804-L821
6,466
mongodb/node-mongodb-native
lib/operations/collection_ops.js
indexInformation
function indexInformation(coll, options, callback) { indexInformationDb(coll.s.db, coll.s.name, options, callback); }
javascript
function indexInformation(coll, options, callback) { indexInformationDb(coll.s.db, coll.s.name, options, callback); }
[ "function", "indexInformation", "(", "coll", ",", "options", ",", "callback", ")", "{", "indexInformationDb", "(", "coll", ".", "s", ".", "db", ",", "coll", ".", "s", ".", "name", ",", "options", ",", "callback", ")", ";", "}" ]
Retrieve this collection's index info. @method @param {Collection} a Collection instance. @param {object} [options] Optional settings. See Collection.prototype.indexInformation for a list of options. @param {Collection~resultCallback} [callback] The command result callback
[ "Retrieve", "this", "collection", "s", "index", "info", "." ]
0afbbccf1bd7d437610c33cbd5523f01bc6bc6e5
https://github.com/mongodb/node-mongodb-native/blob/0afbbccf1bd7d437610c33cbd5523f01bc6bc6e5/lib/operations/collection_ops.js#L831-L833
6,467
mongodb/node-mongodb-native
lib/operations/collection_ops.js
insertOne
function insertOne(coll, doc, options, callback) { if (Array.isArray(doc)) { return callback( MongoError.create({ message: 'doc parameter must be an object', driver: true }) ); } insertDocuments(coll, [doc], options, (err, r) => { if (callback == null) return; if (err && callback) return callback(err); // Workaround for pre 2.6 servers if (r == null) return callback(null, { result: { ok: 1 } }); // Add values to top level to ensure crud spec compatibility r.insertedCount = r.result.n; r.insertedId = doc._id; if (callback) callback(null, r); }); }
javascript
function insertOne(coll, doc, options, callback) { if (Array.isArray(doc)) { return callback( MongoError.create({ message: 'doc parameter must be an object', driver: true }) ); } insertDocuments(coll, [doc], options, (err, r) => { if (callback == null) return; if (err && callback) return callback(err); // Workaround for pre 2.6 servers if (r == null) return callback(null, { result: { ok: 1 } }); // Add values to top level to ensure crud spec compatibility r.insertedCount = r.result.n; r.insertedId = doc._id; if (callback) callback(null, r); }); }
[ "function", "insertOne", "(", "coll", ",", "doc", ",", "options", ",", "callback", ")", "{", "if", "(", "Array", ".", "isArray", "(", "doc", ")", ")", "{", "return", "callback", "(", "MongoError", ".", "create", "(", "{", "message", ":", "'doc parameter must be an object'", ",", "driver", ":", "true", "}", ")", ")", ";", "}", "insertDocuments", "(", "coll", ",", "[", "doc", "]", ",", "options", ",", "(", "err", ",", "r", ")", "=>", "{", "if", "(", "callback", "==", "null", ")", "return", ";", "if", "(", "err", "&&", "callback", ")", "return", "callback", "(", "err", ")", ";", "// Workaround for pre 2.6 servers", "if", "(", "r", "==", "null", ")", "return", "callback", "(", "null", ",", "{", "result", ":", "{", "ok", ":", "1", "}", "}", ")", ";", "// Add values to top level to ensure crud spec compatibility", "r", ".", "insertedCount", "=", "r", ".", "result", ".", "n", ";", "r", ".", "insertedId", "=", "doc", ".", "_id", ";", "if", "(", "callback", ")", "callback", "(", "null", ",", "r", ")", ";", "}", ")", ";", "}" ]
Insert a single document into the collection. See Collection.prototype.insertOne for more information. @method @param {Collection} a Collection instance. @param {object} doc Document to insert. @param {object} [options] Optional settings. See Collection.prototype.insertOne for a list of options. @param {Collection~insertOneWriteOpCallback} [callback] The command result callback
[ "Insert", "a", "single", "document", "into", "the", "collection", ".", "See", "Collection", ".", "prototype", ".", "insertOne", "for", "more", "information", "." ]
0afbbccf1bd7d437610c33cbd5523f01bc6bc6e5
https://github.com/mongodb/node-mongodb-native/blob/0afbbccf1bd7d437610c33cbd5523f01bc6bc6e5/lib/operations/collection_ops.js#L876-L893
6,468
mongodb/node-mongodb-native
lib/operations/collection_ops.js
isCapped
function isCapped(coll, options, callback) { optionsOp(coll, options, (err, document) => { if (err) return handleCallback(callback, err); handleCallback(callback, null, !!(document && document.capped)); }); }
javascript
function isCapped(coll, options, callback) { optionsOp(coll, options, (err, document) => { if (err) return handleCallback(callback, err); handleCallback(callback, null, !!(document && document.capped)); }); }
[ "function", "isCapped", "(", "coll", ",", "options", ",", "callback", ")", "{", "optionsOp", "(", "coll", ",", "options", ",", "(", "err", ",", "document", ")", "=>", "{", "if", "(", "err", ")", "return", "handleCallback", "(", "callback", ",", "err", ")", ";", "handleCallback", "(", "callback", ",", "null", ",", "!", "!", "(", "document", "&&", "document", ".", "capped", ")", ")", ";", "}", ")", ";", "}" ]
Determine whether the collection is a capped collection. @method @param {Collection} a Collection instance. @param {Object} [options] Optional settings. See Collection.prototype.isCapped for a list of options. @param {Collection~resultCallback} [callback] The results callback
[ "Determine", "whether", "the", "collection", "is", "a", "capped", "collection", "." ]
0afbbccf1bd7d437610c33cbd5523f01bc6bc6e5
https://github.com/mongodb/node-mongodb-native/blob/0afbbccf1bd7d437610c33cbd5523f01bc6bc6e5/lib/operations/collection_ops.js#L954-L959
6,469
mongodb/node-mongodb-native
lib/operations/collection_ops.js
optionsOp
function optionsOp(coll, opts, callback) { coll.s.db.listCollections({ name: coll.s.name }, opts).toArray((err, collections) => { if (err) return handleCallback(callback, err); if (collections.length === 0) { return handleCallback( callback, MongoError.create({ message: `collection ${coll.s.namespace} not found`, driver: true }) ); } handleCallback(callback, err, collections[0].options || null); }); }
javascript
function optionsOp(coll, opts, callback) { coll.s.db.listCollections({ name: coll.s.name }, opts).toArray((err, collections) => { if (err) return handleCallback(callback, err); if (collections.length === 0) { return handleCallback( callback, MongoError.create({ message: `collection ${coll.s.namespace} not found`, driver: true }) ); } handleCallback(callback, err, collections[0].options || null); }); }
[ "function", "optionsOp", "(", "coll", ",", "opts", ",", "callback", ")", "{", "coll", ".", "s", ".", "db", ".", "listCollections", "(", "{", "name", ":", "coll", ".", "s", ".", "name", "}", ",", "opts", ")", ".", "toArray", "(", "(", "err", ",", "collections", ")", "=>", "{", "if", "(", "err", ")", "return", "handleCallback", "(", "callback", ",", "err", ")", ";", "if", "(", "collections", ".", "length", "===", "0", ")", "{", "return", "handleCallback", "(", "callback", ",", "MongoError", ".", "create", "(", "{", "message", ":", "`", "${", "coll", ".", "s", ".", "namespace", "}", "`", ",", "driver", ":", "true", "}", ")", ")", ";", "}", "handleCallback", "(", "callback", ",", "err", ",", "collections", "[", "0", "]", ".", "options", "||", "null", ")", ";", "}", ")", ";", "}" ]
Return the options of the collection. @method @param {Collection} a Collection instance. @param {Object} [options] Optional settings. See Collection.prototype.options for a list of options. @param {Collection~resultCallback} [callback] The results callback
[ "Return", "the", "options", "of", "the", "collection", "." ]
0afbbccf1bd7d437610c33cbd5523f01bc6bc6e5
https://github.com/mongodb/node-mongodb-native/blob/0afbbccf1bd7d437610c33cbd5523f01bc6bc6e5/lib/operations/collection_ops.js#L1083-L1095
6,470
mongodb/node-mongodb-native
lib/operations/collection_ops.js
parallelCollectionScan
function parallelCollectionScan(coll, options, callback) { // Create command object const commandObject = { parallelCollectionScan: coll.s.name, numCursors: options.numCursors }; // Do we have a readConcern specified decorateWithReadConcern(commandObject, coll, options); // Store the raw value const raw = options.raw; delete options['raw']; // Execute the command executeCommand(coll.s.db, commandObject, options, (err, result) => { if (err) return handleCallback(callback, err, null); if (result == null) return handleCallback( callback, new Error('no result returned for parallelCollectionScan'), null ); options = Object.assign({ explicitlyIgnoreSession: true }, options); const cursors = []; // Add the raw back to the option if (raw) options.raw = raw; // Create command cursors for each item for (let i = 0; i < result.cursors.length; i++) { const rawId = result.cursors[i].cursor.id; // Convert cursorId to Long if needed const cursorId = typeof rawId === 'number' ? Long.fromNumber(rawId) : rawId; // Add a command cursor cursors.push(coll.s.topology.cursor(coll.s.namespace, cursorId, options)); } handleCallback(callback, null, cursors); }); }
javascript
function parallelCollectionScan(coll, options, callback) { // Create command object const commandObject = { parallelCollectionScan: coll.s.name, numCursors: options.numCursors }; // Do we have a readConcern specified decorateWithReadConcern(commandObject, coll, options); // Store the raw value const raw = options.raw; delete options['raw']; // Execute the command executeCommand(coll.s.db, commandObject, options, (err, result) => { if (err) return handleCallback(callback, err, null); if (result == null) return handleCallback( callback, new Error('no result returned for parallelCollectionScan'), null ); options = Object.assign({ explicitlyIgnoreSession: true }, options); const cursors = []; // Add the raw back to the option if (raw) options.raw = raw; // Create command cursors for each item for (let i = 0; i < result.cursors.length; i++) { const rawId = result.cursors[i].cursor.id; // Convert cursorId to Long if needed const cursorId = typeof rawId === 'number' ? Long.fromNumber(rawId) : rawId; // Add a command cursor cursors.push(coll.s.topology.cursor(coll.s.namespace, cursorId, options)); } handleCallback(callback, null, cursors); }); }
[ "function", "parallelCollectionScan", "(", "coll", ",", "options", ",", "callback", ")", "{", "// Create command object", "const", "commandObject", "=", "{", "parallelCollectionScan", ":", "coll", ".", "s", ".", "name", ",", "numCursors", ":", "options", ".", "numCursors", "}", ";", "// Do we have a readConcern specified", "decorateWithReadConcern", "(", "commandObject", ",", "coll", ",", "options", ")", ";", "// Store the raw value", "const", "raw", "=", "options", ".", "raw", ";", "delete", "options", "[", "'raw'", "]", ";", "// Execute the command", "executeCommand", "(", "coll", ".", "s", ".", "db", ",", "commandObject", ",", "options", ",", "(", "err", ",", "result", ")", "=>", "{", "if", "(", "err", ")", "return", "handleCallback", "(", "callback", ",", "err", ",", "null", ")", ";", "if", "(", "result", "==", "null", ")", "return", "handleCallback", "(", "callback", ",", "new", "Error", "(", "'no result returned for parallelCollectionScan'", ")", ",", "null", ")", ";", "options", "=", "Object", ".", "assign", "(", "{", "explicitlyIgnoreSession", ":", "true", "}", ",", "options", ")", ";", "const", "cursors", "=", "[", "]", ";", "// Add the raw back to the option", "if", "(", "raw", ")", "options", ".", "raw", "=", "raw", ";", "// Create command cursors for each item", "for", "(", "let", "i", "=", "0", ";", "i", "<", "result", ".", "cursors", ".", "length", ";", "i", "++", ")", "{", "const", "rawId", "=", "result", ".", "cursors", "[", "i", "]", ".", "cursor", ".", "id", ";", "// Convert cursorId to Long if needed", "const", "cursorId", "=", "typeof", "rawId", "===", "'number'", "?", "Long", ".", "fromNumber", "(", "rawId", ")", ":", "rawId", ";", "// Add a command cursor", "cursors", ".", "push", "(", "coll", ".", "s", ".", "topology", ".", "cursor", "(", "coll", ".", "s", ".", "namespace", ",", "cursorId", ",", "options", ")", ")", ";", "}", "handleCallback", "(", "callback", ",", "null", ",", "cursors", ")", ";", "}", ")", ";", "}" ]
Return N parallel cursors for a collection to allow parallel reading of the entire collection. There are no ordering guarantees for returned results. @method @param {Collection} a Collection instance. @param {object} [options] Optional settings. See Collection.prototype.parallelCollectionScan for a list of options. @param {Collection~parallelCollectionScanCallback} [callback] The command result callback
[ "Return", "N", "parallel", "cursors", "for", "a", "collection", "to", "allow", "parallel", "reading", "of", "the", "entire", "collection", ".", "There", "are", "no", "ordering", "guarantees", "for", "returned", "results", "." ]
0afbbccf1bd7d437610c33cbd5523f01bc6bc6e5
https://github.com/mongodb/node-mongodb-native/blob/0afbbccf1bd7d437610c33cbd5523f01bc6bc6e5/lib/operations/collection_ops.js#L1106-L1146
6,471
mongodb/node-mongodb-native
lib/operations/collection_ops.js
prepareDocs
function prepareDocs(coll, docs, options) { const forceServerObjectId = typeof options.forceServerObjectId === 'boolean' ? options.forceServerObjectId : coll.s.db.options.forceServerObjectId; // no need to modify the docs if server sets the ObjectId if (forceServerObjectId === true) { return docs; } return docs.map(doc => { if (forceServerObjectId !== true && doc._id == null) { doc._id = coll.s.pkFactory.createPk(); } return doc; }); }
javascript
function prepareDocs(coll, docs, options) { const forceServerObjectId = typeof options.forceServerObjectId === 'boolean' ? options.forceServerObjectId : coll.s.db.options.forceServerObjectId; // no need to modify the docs if server sets the ObjectId if (forceServerObjectId === true) { return docs; } return docs.map(doc => { if (forceServerObjectId !== true && doc._id == null) { doc._id = coll.s.pkFactory.createPk(); } return doc; }); }
[ "function", "prepareDocs", "(", "coll", ",", "docs", ",", "options", ")", "{", "const", "forceServerObjectId", "=", "typeof", "options", ".", "forceServerObjectId", "===", "'boolean'", "?", "options", ".", "forceServerObjectId", ":", "coll", ".", "s", ".", "db", ".", "options", ".", "forceServerObjectId", ";", "// no need to modify the docs if server sets the ObjectId", "if", "(", "forceServerObjectId", "===", "true", ")", "{", "return", "docs", ";", "}", "return", "docs", ".", "map", "(", "doc", "=>", "{", "if", "(", "forceServerObjectId", "!==", "true", "&&", "doc", ".", "_id", "==", "null", ")", "{", "doc", ".", "_id", "=", "coll", ".", "s", ".", "pkFactory", ".", "createPk", "(", ")", ";", "}", "return", "doc", ";", "}", ")", ";", "}" ]
modifies documents before being inserted or updated
[ "modifies", "documents", "before", "being", "inserted", "or", "updated" ]
0afbbccf1bd7d437610c33cbd5523f01bc6bc6e5
https://github.com/mongodb/node-mongodb-native/blob/0afbbccf1bd7d437610c33cbd5523f01bc6bc6e5/lib/operations/collection_ops.js#L1149-L1167
6,472
mongodb/node-mongodb-native
lib/operations/collection_ops.js
processScope
function processScope(scope) { if (!isObject(scope) || scope._bsontype === 'ObjectID') { return scope; } const keys = Object.keys(scope); let key; const new_scope = {}; for (let i = keys.length - 1; i >= 0; i--) { key = keys[i]; if ('function' === typeof scope[key]) { new_scope[key] = new Code(String(scope[key])); } else { new_scope[key] = processScope(scope[key]); } } return new_scope; }
javascript
function processScope(scope) { if (!isObject(scope) || scope._bsontype === 'ObjectID') { return scope; } const keys = Object.keys(scope); let key; const new_scope = {}; for (let i = keys.length - 1; i >= 0; i--) { key = keys[i]; if ('function' === typeof scope[key]) { new_scope[key] = new Code(String(scope[key])); } else { new_scope[key] = processScope(scope[key]); } } return new_scope; }
[ "function", "processScope", "(", "scope", ")", "{", "if", "(", "!", "isObject", "(", "scope", ")", "||", "scope", ".", "_bsontype", "===", "'ObjectID'", ")", "{", "return", "scope", ";", "}", "const", "keys", "=", "Object", ".", "keys", "(", "scope", ")", ";", "let", "key", ";", "const", "new_scope", "=", "{", "}", ";", "for", "(", "let", "i", "=", "keys", ".", "length", "-", "1", ";", "i", ">=", "0", ";", "i", "--", ")", "{", "key", "=", "keys", "[", "i", "]", ";", "if", "(", "'function'", "===", "typeof", "scope", "[", "key", "]", ")", "{", "new_scope", "[", "key", "]", "=", "new", "Code", "(", "String", "(", "scope", "[", "key", "]", ")", ")", ";", "}", "else", "{", "new_scope", "[", "key", "]", "=", "processScope", "(", "scope", "[", "key", "]", ")", ";", "}", "}", "return", "new_scope", ";", "}" ]
Functions that are passed as scope args must be converted to Code instances. @ignore
[ "Functions", "that", "are", "passed", "as", "scope", "args", "must", "be", "converted", "to", "Code", "instances", "." ]
0afbbccf1bd7d437610c33cbd5523f01bc6bc6e5
https://github.com/mongodb/node-mongodb-native/blob/0afbbccf1bd7d437610c33cbd5523f01bc6bc6e5/lib/operations/collection_ops.js#L1174-L1193
6,473
mongodb/node-mongodb-native
lib/operations/collection_ops.js
reIndex
function reIndex(coll, options, callback) { // Reindex const cmd = { reIndex: coll.s.name }; // Execute the command executeCommand(coll.s.db, cmd, options, (err, result) => { if (callback == null) return; if (err) return handleCallback(callback, err, null); handleCallback(callback, null, result.ok ? true : false); }); }
javascript
function reIndex(coll, options, callback) { // Reindex const cmd = { reIndex: coll.s.name }; // Execute the command executeCommand(coll.s.db, cmd, options, (err, result) => { if (callback == null) return; if (err) return handleCallback(callback, err, null); handleCallback(callback, null, result.ok ? true : false); }); }
[ "function", "reIndex", "(", "coll", ",", "options", ",", "callback", ")", "{", "// Reindex", "const", "cmd", "=", "{", "reIndex", ":", "coll", ".", "s", ".", "name", "}", ";", "// Execute the command", "executeCommand", "(", "coll", ".", "s", ".", "db", ",", "cmd", ",", "options", ",", "(", "err", ",", "result", ")", "=>", "{", "if", "(", "callback", "==", "null", ")", "return", ";", "if", "(", "err", ")", "return", "handleCallback", "(", "callback", ",", "err", ",", "null", ")", ";", "handleCallback", "(", "callback", ",", "null", ",", "result", ".", "ok", "?", "true", ":", "false", ")", ";", "}", ")", ";", "}" ]
Reindex all indexes on the collection. @method @param {Collection} a Collection instance. @param {Object} [options] Optional settings. See Collection.prototype.reIndex for a list of options. @param {Collection~resultCallback} [callback] The command result callback
[ "Reindex", "all", "indexes", "on", "the", "collection", "." ]
0afbbccf1bd7d437610c33cbd5523f01bc6bc6e5
https://github.com/mongodb/node-mongodb-native/blob/0afbbccf1bd7d437610c33cbd5523f01bc6bc6e5/lib/operations/collection_ops.js#L1203-L1213
6,474
mongodb/node-mongodb-native
lib/operations/collection_ops.js
replaceOne
function replaceOne(coll, filter, doc, options, callback) { // Set single document update options.multi = false; // Execute update updateDocuments(coll, filter, doc, options, (err, r) => { if (callback == null) return; if (err && callback) return callback(err); if (r == null) return callback(null, { result: { ok: 1 } }); r.modifiedCount = r.result.nModified != null ? r.result.nModified : r.result.n; r.upsertedId = Array.isArray(r.result.upserted) && r.result.upserted.length > 0 ? r.result.upserted[0] // FIXME(major): should be `r.result.upserted[0]._id` : null; r.upsertedCount = Array.isArray(r.result.upserted) && r.result.upserted.length ? r.result.upserted.length : 0; r.matchedCount = Array.isArray(r.result.upserted) && r.result.upserted.length > 0 ? 0 : r.result.n; r.ops = [doc]; if (callback) callback(null, r); }); }
javascript
function replaceOne(coll, filter, doc, options, callback) { // Set single document update options.multi = false; // Execute update updateDocuments(coll, filter, doc, options, (err, r) => { if (callback == null) return; if (err && callback) return callback(err); if (r == null) return callback(null, { result: { ok: 1 } }); r.modifiedCount = r.result.nModified != null ? r.result.nModified : r.result.n; r.upsertedId = Array.isArray(r.result.upserted) && r.result.upserted.length > 0 ? r.result.upserted[0] // FIXME(major): should be `r.result.upserted[0]._id` : null; r.upsertedCount = Array.isArray(r.result.upserted) && r.result.upserted.length ? r.result.upserted.length : 0; r.matchedCount = Array.isArray(r.result.upserted) && r.result.upserted.length > 0 ? 0 : r.result.n; r.ops = [doc]; if (callback) callback(null, r); }); }
[ "function", "replaceOne", "(", "coll", ",", "filter", ",", "doc", ",", "options", ",", "callback", ")", "{", "// Set single document update", "options", ".", "multi", "=", "false", ";", "// Execute update", "updateDocuments", "(", "coll", ",", "filter", ",", "doc", ",", "options", ",", "(", "err", ",", "r", ")", "=>", "{", "if", "(", "callback", "==", "null", ")", "return", ";", "if", "(", "err", "&&", "callback", ")", "return", "callback", "(", "err", ")", ";", "if", "(", "r", "==", "null", ")", "return", "callback", "(", "null", ",", "{", "result", ":", "{", "ok", ":", "1", "}", "}", ")", ";", "r", ".", "modifiedCount", "=", "r", ".", "result", ".", "nModified", "!=", "null", "?", "r", ".", "result", ".", "nModified", ":", "r", ".", "result", ".", "n", ";", "r", ".", "upsertedId", "=", "Array", ".", "isArray", "(", "r", ".", "result", ".", "upserted", ")", "&&", "r", ".", "result", ".", "upserted", ".", "length", ">", "0", "?", "r", ".", "result", ".", "upserted", "[", "0", "]", "// FIXME(major): should be `r.result.upserted[0]._id`", ":", "null", ";", "r", ".", "upsertedCount", "=", "Array", ".", "isArray", "(", "r", ".", "result", ".", "upserted", ")", "&&", "r", ".", "result", ".", "upserted", ".", "length", "?", "r", ".", "result", ".", "upserted", ".", "length", ":", "0", ";", "r", ".", "matchedCount", "=", "Array", ".", "isArray", "(", "r", ".", "result", ".", "upserted", ")", "&&", "r", ".", "result", ".", "upserted", ".", "length", ">", "0", "?", "0", ":", "r", ".", "result", ".", "n", ";", "r", ".", "ops", "=", "[", "doc", "]", ";", "if", "(", "callback", ")", "callback", "(", "null", ",", "r", ")", ";", "}", ")", ";", "}" ]
Replace a document in the collection. @method @param {Collection} a Collection instance. @param {object} filter The Filter used to select the document to update @param {object} doc The Document that replaces the matching document @param {object} [options] Optional settings. See Collection.prototype.replaceOne for a list of options. @param {Collection~updateWriteOpCallback} [callback] The command result callback
[ "Replace", "a", "document", "in", "the", "collection", "." ]
0afbbccf1bd7d437610c33cbd5523f01bc6bc6e5
https://github.com/mongodb/node-mongodb-native/blob/0afbbccf1bd7d437610c33cbd5523f01bc6bc6e5/lib/operations/collection_ops.js#L1319-L1341
6,475
mongodb/node-mongodb-native
lib/operations/collection_ops.js
save
function save(coll, doc, options, callback) { // Get the write concern options const finalOptions = applyWriteConcern( Object.assign({}, options), { db: coll.s.db, collection: coll }, options ); // Establish if we need to perform an insert or update if (doc._id != null) { finalOptions.upsert = true; return updateDocuments(coll, { _id: doc._id }, doc, finalOptions, callback); } // Insert the document insertDocuments(coll, [doc], finalOptions, (err, result) => { if (callback == null) return; if (doc == null) return handleCallback(callback, null, null); if (err) return handleCallback(callback, err, null); handleCallback(callback, null, result); }); }
javascript
function save(coll, doc, options, callback) { // Get the write concern options const finalOptions = applyWriteConcern( Object.assign({}, options), { db: coll.s.db, collection: coll }, options ); // Establish if we need to perform an insert or update if (doc._id != null) { finalOptions.upsert = true; return updateDocuments(coll, { _id: doc._id }, doc, finalOptions, callback); } // Insert the document insertDocuments(coll, [doc], finalOptions, (err, result) => { if (callback == null) return; if (doc == null) return handleCallback(callback, null, null); if (err) return handleCallback(callback, err, null); handleCallback(callback, null, result); }); }
[ "function", "save", "(", "coll", ",", "doc", ",", "options", ",", "callback", ")", "{", "// Get the write concern options", "const", "finalOptions", "=", "applyWriteConcern", "(", "Object", ".", "assign", "(", "{", "}", ",", "options", ")", ",", "{", "db", ":", "coll", ".", "s", ".", "db", ",", "collection", ":", "coll", "}", ",", "options", ")", ";", "// Establish if we need to perform an insert or update", "if", "(", "doc", ".", "_id", "!=", "null", ")", "{", "finalOptions", ".", "upsert", "=", "true", ";", "return", "updateDocuments", "(", "coll", ",", "{", "_id", ":", "doc", ".", "_id", "}", ",", "doc", ",", "finalOptions", ",", "callback", ")", ";", "}", "// Insert the document", "insertDocuments", "(", "coll", ",", "[", "doc", "]", ",", "finalOptions", ",", "(", "err", ",", "result", ")", "=>", "{", "if", "(", "callback", "==", "null", ")", "return", ";", "if", "(", "doc", "==", "null", ")", "return", "handleCallback", "(", "callback", ",", "null", ",", "null", ")", ";", "if", "(", "err", ")", "return", "handleCallback", "(", "callback", ",", "err", ",", "null", ")", ";", "handleCallback", "(", "callback", ",", "null", ",", "result", ")", ";", "}", ")", ";", "}" ]
Save a document. @method @param {Collection} a Collection instance. @param {object} doc Document to save @param {object} [options] Optional settings. See Collection.prototype.save for a list of options. @param {Collection~writeOpCallback} [callback] The command result callback @deprecated use insertOne, insertMany, updateOne or updateMany
[ "Save", "a", "document", "." ]
0afbbccf1bd7d437610c33cbd5523f01bc6bc6e5
https://github.com/mongodb/node-mongodb-native/blob/0afbbccf1bd7d437610c33cbd5523f01bc6bc6e5/lib/operations/collection_ops.js#L1353-L1373
6,476
mongodb/node-mongodb-native
lib/operations/collection_ops.js
stats
function stats(coll, options, callback) { // Build command object const commandObject = { collStats: coll.s.name }; // Check if we have the scale value if (options['scale'] != null) commandObject['scale'] = options['scale']; options = Object.assign({}, options); // Ensure we have the right read preference inheritance options.readPreference = resolveReadPreference(options, { db: coll.s.db, collection: coll }); // Execute the command executeCommand(coll.s.db, commandObject, options, callback); }
javascript
function stats(coll, options, callback) { // Build command object const commandObject = { collStats: coll.s.name }; // Check if we have the scale value if (options['scale'] != null) commandObject['scale'] = options['scale']; options = Object.assign({}, options); // Ensure we have the right read preference inheritance options.readPreference = resolveReadPreference(options, { db: coll.s.db, collection: coll }); // Execute the command executeCommand(coll.s.db, commandObject, options, callback); }
[ "function", "stats", "(", "coll", ",", "options", ",", "callback", ")", "{", "// Build command object", "const", "commandObject", "=", "{", "collStats", ":", "coll", ".", "s", ".", "name", "}", ";", "// Check if we have the scale value", "if", "(", "options", "[", "'scale'", "]", "!=", "null", ")", "commandObject", "[", "'scale'", "]", "=", "options", "[", "'scale'", "]", ";", "options", "=", "Object", ".", "assign", "(", "{", "}", ",", "options", ")", ";", "// Ensure we have the right read preference inheritance", "options", ".", "readPreference", "=", "resolveReadPreference", "(", "options", ",", "{", "db", ":", "coll", ".", "s", ".", "db", ",", "collection", ":", "coll", "}", ")", ";", "// Execute the command", "executeCommand", "(", "coll", ".", "s", ".", "db", ",", "commandObject", ",", "options", ",", "callback", ")", ";", "}" ]
Get all the collection statistics. @method @param {Collection} a Collection instance. @param {object} [options] Optional settings. See Collection.prototype.stats for a list of options. @param {Collection~resultCallback} [callback] The collection result callback
[ "Get", "all", "the", "collection", "statistics", "." ]
0afbbccf1bd7d437610c33cbd5523f01bc6bc6e5
https://github.com/mongodb/node-mongodb-native/blob/0afbbccf1bd7d437610c33cbd5523f01bc6bc6e5/lib/operations/collection_ops.js#L1383-L1398
6,477
mongodb/node-mongodb-native
lib/operations/collection_ops.js
updateMany
function updateMany(coll, filter, update, options, callback) { // Set single document update options.multi = true; // Execute update updateDocuments(coll, filter, update, options, (err, r) => updateCallback(err, r, callback)); }
javascript
function updateMany(coll, filter, update, options, callback) { // Set single document update options.multi = true; // Execute update updateDocuments(coll, filter, update, options, (err, r) => updateCallback(err, r, callback)); }
[ "function", "updateMany", "(", "coll", ",", "filter", ",", "update", ",", "options", ",", "callback", ")", "{", "// Set single document update", "options", ".", "multi", "=", "true", ";", "// Execute update", "updateDocuments", "(", "coll", ",", "filter", ",", "update", ",", "options", ",", "(", "err", ",", "r", ")", "=>", "updateCallback", "(", "err", ",", "r", ",", "callback", ")", ")", ";", "}" ]
Update multiple documents in the collection. @method @param {Collection} a Collection instance. @param {object} filter The Filter used to select the documents to update @param {object} update The update operations to be applied to the document @param {object} [options] Optional settings. See Collection.prototype.updateMany for a list of options. @param {Collection~updateWriteOpCallback} [callback] The command result callback
[ "Update", "multiple", "documents", "in", "the", "collection", "." ]
0afbbccf1bd7d437610c33cbd5523f01bc6bc6e5
https://github.com/mongodb/node-mongodb-native/blob/0afbbccf1bd7d437610c33cbd5523f01bc6bc6e5/lib/operations/collection_ops.js#L1481-L1486
6,478
mongodb/node-mongodb-native
lib/operations/collection_ops.js
updateOne
function updateOne(coll, filter, update, options, callback) { // Set single document update options.multi = false; // Execute update updateDocuments(coll, filter, update, options, (err, r) => updateCallback(err, r, callback)); }
javascript
function updateOne(coll, filter, update, options, callback) { // Set single document update options.multi = false; // Execute update updateDocuments(coll, filter, update, options, (err, r) => updateCallback(err, r, callback)); }
[ "function", "updateOne", "(", "coll", ",", "filter", ",", "update", ",", "options", ",", "callback", ")", "{", "// Set single document update", "options", ".", "multi", "=", "false", ";", "// Execute update", "updateDocuments", "(", "coll", ",", "filter", ",", "update", ",", "options", ",", "(", "err", ",", "r", ")", "=>", "updateCallback", "(", "err", ",", "r", ",", "callback", ")", ")", ";", "}" ]
Update a single document in the collection. @method @param {Collection} a Collection instance. @param {object} filter The Filter used to select the document to update @param {object} update The update operations to be applied to the document @param {object} [options] Optional settings. See Collection.prototype.updateOne for a list of options. @param {Collection~updateWriteOpCallback} [callback] The command result callback
[ "Update", "a", "single", "document", "in", "the", "collection", "." ]
0afbbccf1bd7d437610c33cbd5523f01bc6bc6e5
https://github.com/mongodb/node-mongodb-native/blob/0afbbccf1bd7d437610c33cbd5523f01bc6bc6e5/lib/operations/collection_ops.js#L1498-L1503
6,479
mongodb/node-mongodb-native
lib/topologies/topology_base.js
function(topology, storeOptions) { var self = this; var storedOps = []; storeOptions = storeOptions || { force: false, bufferMaxEntries: -1 }; // Internal state this.s = { storedOps: storedOps, storeOptions: storeOptions, topology: topology }; Object.defineProperty(this, 'length', { enumerable: true, get: function() { return self.s.storedOps.length; } }); }
javascript
function(topology, storeOptions) { var self = this; var storedOps = []; storeOptions = storeOptions || { force: false, bufferMaxEntries: -1 }; // Internal state this.s = { storedOps: storedOps, storeOptions: storeOptions, topology: topology }; Object.defineProperty(this, 'length', { enumerable: true, get: function() { return self.s.storedOps.length; } }); }
[ "function", "(", "topology", ",", "storeOptions", ")", "{", "var", "self", "=", "this", ";", "var", "storedOps", "=", "[", "]", ";", "storeOptions", "=", "storeOptions", "||", "{", "force", ":", "false", ",", "bufferMaxEntries", ":", "-", "1", "}", ";", "// Internal state", "this", ".", "s", "=", "{", "storedOps", ":", "storedOps", ",", "storeOptions", ":", "storeOptions", ",", "topology", ":", "topology", "}", ";", "Object", ".", "defineProperty", "(", "this", ",", "'length'", ",", "{", "enumerable", ":", "true", ",", "get", ":", "function", "(", ")", "{", "return", "self", ".", "s", ".", "storedOps", ".", "length", ";", "}", "}", ")", ";", "}" ]
The store of ops
[ "The", "store", "of", "ops" ]
0afbbccf1bd7d437610c33cbd5523f01bc6bc6e5
https://github.com/mongodb/node-mongodb-native/blob/0afbbccf1bd7d437610c33cbd5523f01bc6bc6e5/lib/topologies/topology_base.js#L11-L29
6,480
mongodb/node-mongodb-native
lib/gridfs-stream/upload.js
GridFSBucketWriteStream
function GridFSBucketWriteStream(bucket, filename, options) { options = options || {}; this.bucket = bucket; this.chunks = bucket.s._chunksCollection; this.filename = filename; this.files = bucket.s._filesCollection; this.options = options; // Signals the write is all done this.done = false; this.id = options.id ? options.id : core.BSON.ObjectId(); this.chunkSizeBytes = this.options.chunkSizeBytes; this.bufToStore = Buffer.alloc(this.chunkSizeBytes); this.length = 0; this.md5 = !options.disableMD5 && crypto.createHash('md5'); this.n = 0; this.pos = 0; this.state = { streamEnd: false, outstandingRequests: 0, errored: false, aborted: false, promiseLibrary: this.bucket.s.promiseLibrary }; if (!this.bucket.s.calledOpenUploadStream) { this.bucket.s.calledOpenUploadStream = true; var _this = this; checkIndexes(this, function() { _this.bucket.s.checkedIndexes = true; _this.bucket.emit('index'); }); } }
javascript
function GridFSBucketWriteStream(bucket, filename, options) { options = options || {}; this.bucket = bucket; this.chunks = bucket.s._chunksCollection; this.filename = filename; this.files = bucket.s._filesCollection; this.options = options; // Signals the write is all done this.done = false; this.id = options.id ? options.id : core.BSON.ObjectId(); this.chunkSizeBytes = this.options.chunkSizeBytes; this.bufToStore = Buffer.alloc(this.chunkSizeBytes); this.length = 0; this.md5 = !options.disableMD5 && crypto.createHash('md5'); this.n = 0; this.pos = 0; this.state = { streamEnd: false, outstandingRequests: 0, errored: false, aborted: false, promiseLibrary: this.bucket.s.promiseLibrary }; if (!this.bucket.s.calledOpenUploadStream) { this.bucket.s.calledOpenUploadStream = true; var _this = this; checkIndexes(this, function() { _this.bucket.s.checkedIndexes = true; _this.bucket.emit('index'); }); } }
[ "function", "GridFSBucketWriteStream", "(", "bucket", ",", "filename", ",", "options", ")", "{", "options", "=", "options", "||", "{", "}", ";", "this", ".", "bucket", "=", "bucket", ";", "this", ".", "chunks", "=", "bucket", ".", "s", ".", "_chunksCollection", ";", "this", ".", "filename", "=", "filename", ";", "this", ".", "files", "=", "bucket", ".", "s", ".", "_filesCollection", ";", "this", ".", "options", "=", "options", ";", "// Signals the write is all done", "this", ".", "done", "=", "false", ";", "this", ".", "id", "=", "options", ".", "id", "?", "options", ".", "id", ":", "core", ".", "BSON", ".", "ObjectId", "(", ")", ";", "this", ".", "chunkSizeBytes", "=", "this", ".", "options", ".", "chunkSizeBytes", ";", "this", ".", "bufToStore", "=", "Buffer", ".", "alloc", "(", "this", ".", "chunkSizeBytes", ")", ";", "this", ".", "length", "=", "0", ";", "this", ".", "md5", "=", "!", "options", ".", "disableMD5", "&&", "crypto", ".", "createHash", "(", "'md5'", ")", ";", "this", ".", "n", "=", "0", ";", "this", ".", "pos", "=", "0", ";", "this", ".", "state", "=", "{", "streamEnd", ":", "false", ",", "outstandingRequests", ":", "0", ",", "errored", ":", "false", ",", "aborted", ":", "false", ",", "promiseLibrary", ":", "this", ".", "bucket", ".", "s", ".", "promiseLibrary", "}", ";", "if", "(", "!", "this", ".", "bucket", ".", "s", ".", "calledOpenUploadStream", ")", "{", "this", ".", "bucket", ".", "s", ".", "calledOpenUploadStream", "=", "true", ";", "var", "_this", "=", "this", ";", "checkIndexes", "(", "this", ",", "function", "(", ")", "{", "_this", ".", "bucket", ".", "s", ".", "checkedIndexes", "=", "true", ";", "_this", ".", "bucket", ".", "emit", "(", "'index'", ")", ";", "}", ")", ";", "}", "}" ]
A writable stream that enables you to write buffers to GridFS. Do not instantiate this class directly. Use `openUploadStream()` instead. @class @param {GridFSBucket} bucket Handle for this stream's corresponding bucket @param {string} filename The value of the 'filename' key in the files doc @param {object} [options] Optional settings. @param {string|number|object} [options.id] Custom file id for the GridFS file. @param {number} [options.chunkSizeBytes] The chunk size to use, in bytes @param {number} [options.w] The write concern @param {number} [options.wtimeout] The write concern timeout @param {number} [options.j] The journal write concern @param {boolean} [options.disableMD5=false] If true, disables adding an md5 field to file data @fires GridFSBucketWriteStream#error @fires GridFSBucketWriteStream#finish @return {GridFSBucketWriteStream} a GridFSBucketWriteStream instance.
[ "A", "writable", "stream", "that", "enables", "you", "to", "write", "buffers", "to", "GridFS", "." ]
0afbbccf1bd7d437610c33cbd5523f01bc6bc6e5
https://github.com/mongodb/node-mongodb-native/blob/0afbbccf1bd7d437610c33cbd5523f01bc6bc6e5/lib/gridfs-stream/upload.js#L33-L67
6,481
mongodb/node-mongodb-native
lib/utils.js
function(options) { var r = null; if (options.readPreference) { r = options.readPreference; } else { return options; } if (typeof r === 'string') { options.readPreference = new ReadPreference(r); } else if (r && !(r instanceof ReadPreference) && typeof r === 'object') { const mode = r.mode || r.preference; if (mode && typeof mode === 'string') { options.readPreference = new ReadPreference(mode, r.tags, { maxStalenessSeconds: r.maxStalenessSeconds }); } } else if (!(r instanceof ReadPreference)) { throw new TypeError('Invalid read preference: ' + r); } return options; }
javascript
function(options) { var r = null; if (options.readPreference) { r = options.readPreference; } else { return options; } if (typeof r === 'string') { options.readPreference = new ReadPreference(r); } else if (r && !(r instanceof ReadPreference) && typeof r === 'object') { const mode = r.mode || r.preference; if (mode && typeof mode === 'string') { options.readPreference = new ReadPreference(mode, r.tags, { maxStalenessSeconds: r.maxStalenessSeconds }); } } else if (!(r instanceof ReadPreference)) { throw new TypeError('Invalid read preference: ' + r); } return options; }
[ "function", "(", "options", ")", "{", "var", "r", "=", "null", ";", "if", "(", "options", ".", "readPreference", ")", "{", "r", "=", "options", ".", "readPreference", ";", "}", "else", "{", "return", "options", ";", "}", "if", "(", "typeof", "r", "===", "'string'", ")", "{", "options", ".", "readPreference", "=", "new", "ReadPreference", "(", "r", ")", ";", "}", "else", "if", "(", "r", "&&", "!", "(", "r", "instanceof", "ReadPreference", ")", "&&", "typeof", "r", "===", "'object'", ")", "{", "const", "mode", "=", "r", ".", "mode", "||", "r", ".", "preference", ";", "if", "(", "mode", "&&", "typeof", "mode", "===", "'string'", ")", "{", "options", ".", "readPreference", "=", "new", "ReadPreference", "(", "mode", ",", "r", ".", "tags", ",", "{", "maxStalenessSeconds", ":", "r", ".", "maxStalenessSeconds", "}", ")", ";", "}", "}", "else", "if", "(", "!", "(", "r", "instanceof", "ReadPreference", ")", ")", "{", "throw", "new", "TypeError", "(", "'Invalid read preference: '", "+", "r", ")", ";", "}", "return", "options", ";", "}" ]
Figure out the read preference
[ "Figure", "out", "the", "read", "preference" ]
0afbbccf1bd7d437610c33cbd5523f01bc6bc6e5
https://github.com/mongodb/node-mongodb-native/blob/0afbbccf1bd7d437610c33cbd5523f01bc6bc6e5/lib/utils.js#L13-L35
6,482
mongodb/node-mongodb-native
lib/utils.js
function(obj, name, value) { Object.defineProperty(obj, name, { enumerable: true, get: function() { return value; } }); }
javascript
function(obj, name, value) { Object.defineProperty(obj, name, { enumerable: true, get: function() { return value; } }); }
[ "function", "(", "obj", ",", "name", ",", "value", ")", "{", "Object", ".", "defineProperty", "(", "obj", ",", "name", ",", "{", "enumerable", ":", "true", ",", "get", ":", "function", "(", ")", "{", "return", "value", ";", "}", "}", ")", ";", "}" ]
Set simple property
[ "Set", "simple", "property" ]
0afbbccf1bd7d437610c33cbd5523f01bc6bc6e5
https://github.com/mongodb/node-mongodb-native/blob/0afbbccf1bd7d437610c33cbd5523f01bc6bc6e5/lib/utils.js#L38-L45
6,483
mongodb/node-mongodb-native
lib/utils.js
function(error) { if (error instanceof Error) return error; var msg = error.err || error.errmsg || error.errMessage || error; var e = MongoError.create({ message: msg, driver: true }); // Get all object keys var keys = typeof error === 'object' ? Object.keys(error) : []; for (var i = 0; i < keys.length; i++) { try { e[keys[i]] = error[keys[i]]; } catch (err) { // continue } } return e; }
javascript
function(error) { if (error instanceof Error) return error; var msg = error.err || error.errmsg || error.errMessage || error; var e = MongoError.create({ message: msg, driver: true }); // Get all object keys var keys = typeof error === 'object' ? Object.keys(error) : []; for (var i = 0; i < keys.length; i++) { try { e[keys[i]] = error[keys[i]]; } catch (err) { // continue } } return e; }
[ "function", "(", "error", ")", "{", "if", "(", "error", "instanceof", "Error", ")", "return", "error", ";", "var", "msg", "=", "error", ".", "err", "||", "error", ".", "errmsg", "||", "error", ".", "errMessage", "||", "error", ";", "var", "e", "=", "MongoError", ".", "create", "(", "{", "message", ":", "msg", ",", "driver", ":", "true", "}", ")", ";", "// Get all object keys", "var", "keys", "=", "typeof", "error", "===", "'object'", "?", "Object", ".", "keys", "(", "error", ")", ":", "[", "]", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "keys", ".", "length", ";", "i", "++", ")", "{", "try", "{", "e", "[", "keys", "[", "i", "]", "]", "=", "error", "[", "keys", "[", "i", "]", "]", ";", "}", "catch", "(", "err", ")", "{", "// continue", "}", "}", "return", "e", ";", "}" ]
Wrap a Mongo error document in an Error instance @ignore @api private
[ "Wrap", "a", "Mongo", "error", "document", "in", "an", "Error", "instance" ]
0afbbccf1bd7d437610c33cbd5523f01bc6bc6e5
https://github.com/mongodb/node-mongodb-native/blob/0afbbccf1bd7d437610c33cbd5523f01bc6bc6e5/lib/utils.js#L145-L163
6,484
mongodb/node-mongodb-native
lib/utils.js
function(fieldOrSpec) { var fieldHash = {}; var indexes = []; var keys; // Get all the fields accordingly if ('string' === typeof fieldOrSpec) { // 'type' indexes.push(fieldOrSpec + '_' + 1); fieldHash[fieldOrSpec] = 1; } else if (Array.isArray(fieldOrSpec)) { fieldOrSpec.forEach(function(f) { if ('string' === typeof f) { // [{location:'2d'}, 'type'] indexes.push(f + '_' + 1); fieldHash[f] = 1; } else if (Array.isArray(f)) { // [['location', '2d'],['type', 1]] indexes.push(f[0] + '_' + (f[1] || 1)); fieldHash[f[0]] = f[1] || 1; } else if (isObject(f)) { // [{location:'2d'}, {type:1}] keys = Object.keys(f); keys.forEach(function(k) { indexes.push(k + '_' + f[k]); fieldHash[k] = f[k]; }); } else { // undefined (ignore) } }); } else if (isObject(fieldOrSpec)) { // {location:'2d', type:1} keys = Object.keys(fieldOrSpec); keys.forEach(function(key) { indexes.push(key + '_' + fieldOrSpec[key]); fieldHash[key] = fieldOrSpec[key]; }); } return { name: indexes.join('_'), keys: keys, fieldHash: fieldHash }; }
javascript
function(fieldOrSpec) { var fieldHash = {}; var indexes = []; var keys; // Get all the fields accordingly if ('string' === typeof fieldOrSpec) { // 'type' indexes.push(fieldOrSpec + '_' + 1); fieldHash[fieldOrSpec] = 1; } else if (Array.isArray(fieldOrSpec)) { fieldOrSpec.forEach(function(f) { if ('string' === typeof f) { // [{location:'2d'}, 'type'] indexes.push(f + '_' + 1); fieldHash[f] = 1; } else if (Array.isArray(f)) { // [['location', '2d'],['type', 1]] indexes.push(f[0] + '_' + (f[1] || 1)); fieldHash[f[0]] = f[1] || 1; } else if (isObject(f)) { // [{location:'2d'}, {type:1}] keys = Object.keys(f); keys.forEach(function(k) { indexes.push(k + '_' + f[k]); fieldHash[k] = f[k]; }); } else { // undefined (ignore) } }); } else if (isObject(fieldOrSpec)) { // {location:'2d', type:1} keys = Object.keys(fieldOrSpec); keys.forEach(function(key) { indexes.push(key + '_' + fieldOrSpec[key]); fieldHash[key] = fieldOrSpec[key]; }); } return { name: indexes.join('_'), keys: keys, fieldHash: fieldHash }; }
[ "function", "(", "fieldOrSpec", ")", "{", "var", "fieldHash", "=", "{", "}", ";", "var", "indexes", "=", "[", "]", ";", "var", "keys", ";", "// Get all the fields accordingly", "if", "(", "'string'", "===", "typeof", "fieldOrSpec", ")", "{", "// 'type'", "indexes", ".", "push", "(", "fieldOrSpec", "+", "'_'", "+", "1", ")", ";", "fieldHash", "[", "fieldOrSpec", "]", "=", "1", ";", "}", "else", "if", "(", "Array", ".", "isArray", "(", "fieldOrSpec", ")", ")", "{", "fieldOrSpec", ".", "forEach", "(", "function", "(", "f", ")", "{", "if", "(", "'string'", "===", "typeof", "f", ")", "{", "// [{location:'2d'}, 'type']", "indexes", ".", "push", "(", "f", "+", "'_'", "+", "1", ")", ";", "fieldHash", "[", "f", "]", "=", "1", ";", "}", "else", "if", "(", "Array", ".", "isArray", "(", "f", ")", ")", "{", "// [['location', '2d'],['type', 1]]", "indexes", ".", "push", "(", "f", "[", "0", "]", "+", "'_'", "+", "(", "f", "[", "1", "]", "||", "1", ")", ")", ";", "fieldHash", "[", "f", "[", "0", "]", "]", "=", "f", "[", "1", "]", "||", "1", ";", "}", "else", "if", "(", "isObject", "(", "f", ")", ")", "{", "// [{location:'2d'}, {type:1}]", "keys", "=", "Object", ".", "keys", "(", "f", ")", ";", "keys", ".", "forEach", "(", "function", "(", "k", ")", "{", "indexes", ".", "push", "(", "k", "+", "'_'", "+", "f", "[", "k", "]", ")", ";", "fieldHash", "[", "k", "]", "=", "f", "[", "k", "]", ";", "}", ")", ";", "}", "else", "{", "// undefined (ignore)", "}", "}", ")", ";", "}", "else", "if", "(", "isObject", "(", "fieldOrSpec", ")", ")", "{", "// {location:'2d', type:1}", "keys", "=", "Object", ".", "keys", "(", "fieldOrSpec", ")", ";", "keys", ".", "forEach", "(", "function", "(", "key", ")", "{", "indexes", ".", "push", "(", "key", "+", "'_'", "+", "fieldOrSpec", "[", "key", "]", ")", ";", "fieldHash", "[", "key", "]", "=", "fieldOrSpec", "[", "key", "]", ";", "}", ")", ";", "}", "return", "{", "name", ":", "indexes", ".", "join", "(", "'_'", ")", ",", "keys", ":", "keys", ",", "fieldHash", ":", "fieldHash", "}", ";", "}" ]
Create index name based on field spec @ignore @api private
[ "Create", "index", "name", "based", "on", "field", "spec" ]
0afbbccf1bd7d437610c33cbd5523f01bc6bc6e5
https://github.com/mongodb/node-mongodb-native/blob/0afbbccf1bd7d437610c33cbd5523f01bc6bc6e5/lib/utils.js#L195-L240
6,485
mongodb/node-mongodb-native
lib/utils.js
function(target, source) { var translations = { // SSL translation options sslCA: 'ca', sslCRL: 'crl', sslValidate: 'rejectUnauthorized', sslKey: 'key', sslCert: 'cert', sslPass: 'passphrase', // SocketTimeout translation options socketTimeoutMS: 'socketTimeout', connectTimeoutMS: 'connectionTimeout', // Replicaset options replicaSet: 'setName', rs_name: 'setName', secondaryAcceptableLatencyMS: 'acceptableLatency', connectWithNoPrimary: 'secondaryOnlyConnectionAllowed', // Mongos options acceptableLatencyMS: 'localThresholdMS' }; for (var name in source) { if (translations[name]) { target[translations[name]] = source[name]; } else { target[name] = source[name]; } } return target; }
javascript
function(target, source) { var translations = { // SSL translation options sslCA: 'ca', sslCRL: 'crl', sslValidate: 'rejectUnauthorized', sslKey: 'key', sslCert: 'cert', sslPass: 'passphrase', // SocketTimeout translation options socketTimeoutMS: 'socketTimeout', connectTimeoutMS: 'connectionTimeout', // Replicaset options replicaSet: 'setName', rs_name: 'setName', secondaryAcceptableLatencyMS: 'acceptableLatency', connectWithNoPrimary: 'secondaryOnlyConnectionAllowed', // Mongos options acceptableLatencyMS: 'localThresholdMS' }; for (var name in source) { if (translations[name]) { target[translations[name]] = source[name]; } else { target[name] = source[name]; } } return target; }
[ "function", "(", "target", ",", "source", ")", "{", "var", "translations", "=", "{", "// SSL translation options", "sslCA", ":", "'ca'", ",", "sslCRL", ":", "'crl'", ",", "sslValidate", ":", "'rejectUnauthorized'", ",", "sslKey", ":", "'key'", ",", "sslCert", ":", "'cert'", ",", "sslPass", ":", "'passphrase'", ",", "// SocketTimeout translation options", "socketTimeoutMS", ":", "'socketTimeout'", ",", "connectTimeoutMS", ":", "'connectionTimeout'", ",", "// Replicaset options", "replicaSet", ":", "'setName'", ",", "rs_name", ":", "'setName'", ",", "secondaryAcceptableLatencyMS", ":", "'acceptableLatency'", ",", "connectWithNoPrimary", ":", "'secondaryOnlyConnectionAllowed'", ",", "// Mongos options", "acceptableLatencyMS", ":", "'localThresholdMS'", "}", ";", "for", "(", "var", "name", "in", "source", ")", "{", "if", "(", "translations", "[", "name", "]", ")", "{", "target", "[", "translations", "[", "name", "]", "]", "=", "source", "[", "name", "]", ";", "}", "else", "{", "target", "[", "name", "]", "=", "source", "[", "name", "]", ";", "}", "}", "return", "target", ";", "}" ]
Merge options with translation
[ "Merge", "options", "with", "translation" ]
0afbbccf1bd7d437610c33cbd5523f01bc6bc6e5
https://github.com/mongodb/node-mongodb-native/blob/0afbbccf1bd7d437610c33cbd5523f01bc6bc6e5/lib/utils.js#L272-L302
6,486
mongodb/node-mongodb-native
lib/utils.js
function(targetOptions, sourceOptions, keys, mergeWriteConcern) { // Mix in any allowed options for (var i = 0; i < keys.length; i++) { if (!targetOptions[keys[i]] && sourceOptions[keys[i]] !== undefined) { targetOptions[keys[i]] = sourceOptions[keys[i]]; } } // No merging of write concern if (!mergeWriteConcern) return targetOptions; // Found no write Concern options var found = false; for (i = 0; i < writeConcernKeys.length; i++) { if (targetOptions[writeConcernKeys[i]]) { found = true; break; } } if (!found) { for (i = 0; i < writeConcernKeys.length; i++) { if (sourceOptions[writeConcernKeys[i]]) { targetOptions[writeConcernKeys[i]] = sourceOptions[writeConcernKeys[i]]; } } } return targetOptions; }
javascript
function(targetOptions, sourceOptions, keys, mergeWriteConcern) { // Mix in any allowed options for (var i = 0; i < keys.length; i++) { if (!targetOptions[keys[i]] && sourceOptions[keys[i]] !== undefined) { targetOptions[keys[i]] = sourceOptions[keys[i]]; } } // No merging of write concern if (!mergeWriteConcern) return targetOptions; // Found no write Concern options var found = false; for (i = 0; i < writeConcernKeys.length; i++) { if (targetOptions[writeConcernKeys[i]]) { found = true; break; } } if (!found) { for (i = 0; i < writeConcernKeys.length; i++) { if (sourceOptions[writeConcernKeys[i]]) { targetOptions[writeConcernKeys[i]] = sourceOptions[writeConcernKeys[i]]; } } } return targetOptions; }
[ "function", "(", "targetOptions", ",", "sourceOptions", ",", "keys", ",", "mergeWriteConcern", ")", "{", "// Mix in any allowed options", "for", "(", "var", "i", "=", "0", ";", "i", "<", "keys", ".", "length", ";", "i", "++", ")", "{", "if", "(", "!", "targetOptions", "[", "keys", "[", "i", "]", "]", "&&", "sourceOptions", "[", "keys", "[", "i", "]", "]", "!==", "undefined", ")", "{", "targetOptions", "[", "keys", "[", "i", "]", "]", "=", "sourceOptions", "[", "keys", "[", "i", "]", "]", ";", "}", "}", "// No merging of write concern", "if", "(", "!", "mergeWriteConcern", ")", "return", "targetOptions", ";", "// Found no write Concern options", "var", "found", "=", "false", ";", "for", "(", "i", "=", "0", ";", "i", "<", "writeConcernKeys", ".", "length", ";", "i", "++", ")", "{", "if", "(", "targetOptions", "[", "writeConcernKeys", "[", "i", "]", "]", ")", "{", "found", "=", "true", ";", "break", ";", "}", "}", "if", "(", "!", "found", ")", "{", "for", "(", "i", "=", "0", ";", "i", "<", "writeConcernKeys", ".", "length", ";", "i", "++", ")", "{", "if", "(", "sourceOptions", "[", "writeConcernKeys", "[", "i", "]", "]", ")", "{", "targetOptions", "[", "writeConcernKeys", "[", "i", "]", "]", "=", "sourceOptions", "[", "writeConcernKeys", "[", "i", "]", "]", ";", "}", "}", "}", "return", "targetOptions", ";", "}" ]
Merge the write concern options
[ "Merge", "the", "write", "concern", "options" ]
0afbbccf1bd7d437610c33cbd5523f01bc6bc6e5
https://github.com/mongodb/node-mongodb-native/blob/0afbbccf1bd7d437610c33cbd5523f01bc6bc6e5/lib/utils.js#L319-L348
6,487
mongodb/node-mongodb-native
lib/utils.js
applyWriteConcern
function applyWriteConcern(target, sources, options) { options = options || {}; const db = sources.db; const coll = sources.collection; if (options.session && options.session.inTransaction()) { // writeConcern is not allowed within a multi-statement transaction if (target.writeConcern) { delete target.writeConcern; } return target; } if (options.w != null || options.j != null || options.fsync != null) { const writeConcern = {}; if (options.w != null) writeConcern.w = options.w; if (options.wtimeout != null) writeConcern.wtimeout = options.wtimeout; if (options.j != null) writeConcern.j = options.j; if (options.fsync != null) writeConcern.fsync = options.fsync; return Object.assign(target, { writeConcern }); } if ( coll && (coll.writeConcern.w != null || coll.writeConcern.j != null || coll.writeConcern.fsync != null) ) { return Object.assign(target, { writeConcern: Object.assign({}, coll.writeConcern) }); } if ( db && (db.writeConcern.w != null || db.writeConcern.j != null || db.writeConcern.fsync != null) ) { return Object.assign(target, { writeConcern: Object.assign({}, db.writeConcern) }); } return target; }
javascript
function applyWriteConcern(target, sources, options) { options = options || {}; const db = sources.db; const coll = sources.collection; if (options.session && options.session.inTransaction()) { // writeConcern is not allowed within a multi-statement transaction if (target.writeConcern) { delete target.writeConcern; } return target; } if (options.w != null || options.j != null || options.fsync != null) { const writeConcern = {}; if (options.w != null) writeConcern.w = options.w; if (options.wtimeout != null) writeConcern.wtimeout = options.wtimeout; if (options.j != null) writeConcern.j = options.j; if (options.fsync != null) writeConcern.fsync = options.fsync; return Object.assign(target, { writeConcern }); } if ( coll && (coll.writeConcern.w != null || coll.writeConcern.j != null || coll.writeConcern.fsync != null) ) { return Object.assign(target, { writeConcern: Object.assign({}, coll.writeConcern) }); } if ( db && (db.writeConcern.w != null || db.writeConcern.j != null || db.writeConcern.fsync != null) ) { return Object.assign(target, { writeConcern: Object.assign({}, db.writeConcern) }); } return target; }
[ "function", "applyWriteConcern", "(", "target", ",", "sources", ",", "options", ")", "{", "options", "=", "options", "||", "{", "}", ";", "const", "db", "=", "sources", ".", "db", ";", "const", "coll", "=", "sources", ".", "collection", ";", "if", "(", "options", ".", "session", "&&", "options", ".", "session", ".", "inTransaction", "(", ")", ")", "{", "// writeConcern is not allowed within a multi-statement transaction", "if", "(", "target", ".", "writeConcern", ")", "{", "delete", "target", ".", "writeConcern", ";", "}", "return", "target", ";", "}", "if", "(", "options", ".", "w", "!=", "null", "||", "options", ".", "j", "!=", "null", "||", "options", ".", "fsync", "!=", "null", ")", "{", "const", "writeConcern", "=", "{", "}", ";", "if", "(", "options", ".", "w", "!=", "null", ")", "writeConcern", ".", "w", "=", "options", ".", "w", ";", "if", "(", "options", ".", "wtimeout", "!=", "null", ")", "writeConcern", ".", "wtimeout", "=", "options", ".", "wtimeout", ";", "if", "(", "options", ".", "j", "!=", "null", ")", "writeConcern", ".", "j", "=", "options", ".", "j", ";", "if", "(", "options", ".", "fsync", "!=", "null", ")", "writeConcern", ".", "fsync", "=", "options", ".", "fsync", ";", "return", "Object", ".", "assign", "(", "target", ",", "{", "writeConcern", "}", ")", ";", "}", "if", "(", "coll", "&&", "(", "coll", ".", "writeConcern", ".", "w", "!=", "null", "||", "coll", ".", "writeConcern", ".", "j", "!=", "null", "||", "coll", ".", "writeConcern", ".", "fsync", "!=", "null", ")", ")", "{", "return", "Object", ".", "assign", "(", "target", ",", "{", "writeConcern", ":", "Object", ".", "assign", "(", "{", "}", ",", "coll", ".", "writeConcern", ")", "}", ")", ";", "}", "if", "(", "db", "&&", "(", "db", ".", "writeConcern", ".", "w", "!=", "null", "||", "db", ".", "writeConcern", ".", "j", "!=", "null", "||", "db", ".", "writeConcern", ".", "fsync", "!=", "null", ")", ")", "{", "return", "Object", ".", "assign", "(", "target", ",", "{", "writeConcern", ":", "Object", ".", "assign", "(", "{", "}", ",", "db", ".", "writeConcern", ")", "}", ")", ";", "}", "return", "target", ";", "}" ]
Applies a write concern to a command based on well defined inheritance rules, optionally detecting support for the write concern in the first place. @param {Object} target the target command we will be applying the write concern to @param {Object} sources sources where we can inherit default write concerns from @param {Object} [options] optional settings passed into a command for write concern overrides @returns {Object} the (now) decorated target
[ "Applies", "a", "write", "concern", "to", "a", "command", "based", "on", "well", "defined", "inheritance", "rules", "optionally", "detecting", "support", "for", "the", "write", "concern", "in", "the", "first", "place", "." ]
0afbbccf1bd7d437610c33cbd5523f01bc6bc6e5
https://github.com/mongodb/node-mongodb-native/blob/0afbbccf1bd7d437610c33cbd5523f01bc6bc6e5/lib/utils.js#L463-L501
6,488
mongodb/node-mongodb-native
lib/utils.js
deprecateOptions
function deprecateOptions(config, fn) { if (process.noDeprecation === true) { return fn; } const msgHandler = config.msgHandler ? config.msgHandler : defaultMsgHandler; const optionsWarned = new Set(); function deprecated() { const options = arguments[config.optionsIndex]; // ensure options is a valid, non-empty object, otherwise short-circuit if (!isObject(options) || Object.keys(options).length === 0) { return fn.apply(this, arguments); } config.deprecatedOptions.forEach(deprecatedOption => { if (options.hasOwnProperty(deprecatedOption) && !optionsWarned.has(deprecatedOption)) { optionsWarned.add(deprecatedOption); const msg = msgHandler(config.name, deprecatedOption); emitDeprecationWarning(msg); if (this && this.getLogger) { const logger = this.getLogger(); if (logger) { logger.warn(msg); } } } }); return fn.apply(this, arguments); } // These lines copied from https://github.com/nodejs/node/blob/25e5ae41688676a5fd29b2e2e7602168eee4ceb5/lib/internal/util.js#L73-L80 // The wrapper will keep the same prototype as fn to maintain prototype chain Object.setPrototypeOf(deprecated, fn); if (fn.prototype) { // Setting this (rather than using Object.setPrototype, as above) ensures // that calling the unwrapped constructor gives an instanceof the wrapped // constructor. deprecated.prototype = fn.prototype; } return deprecated; }
javascript
function deprecateOptions(config, fn) { if (process.noDeprecation === true) { return fn; } const msgHandler = config.msgHandler ? config.msgHandler : defaultMsgHandler; const optionsWarned = new Set(); function deprecated() { const options = arguments[config.optionsIndex]; // ensure options is a valid, non-empty object, otherwise short-circuit if (!isObject(options) || Object.keys(options).length === 0) { return fn.apply(this, arguments); } config.deprecatedOptions.forEach(deprecatedOption => { if (options.hasOwnProperty(deprecatedOption) && !optionsWarned.has(deprecatedOption)) { optionsWarned.add(deprecatedOption); const msg = msgHandler(config.name, deprecatedOption); emitDeprecationWarning(msg); if (this && this.getLogger) { const logger = this.getLogger(); if (logger) { logger.warn(msg); } } } }); return fn.apply(this, arguments); } // These lines copied from https://github.com/nodejs/node/blob/25e5ae41688676a5fd29b2e2e7602168eee4ceb5/lib/internal/util.js#L73-L80 // The wrapper will keep the same prototype as fn to maintain prototype chain Object.setPrototypeOf(deprecated, fn); if (fn.prototype) { // Setting this (rather than using Object.setPrototype, as above) ensures // that calling the unwrapped constructor gives an instanceof the wrapped // constructor. deprecated.prototype = fn.prototype; } return deprecated; }
[ "function", "deprecateOptions", "(", "config", ",", "fn", ")", "{", "if", "(", "process", ".", "noDeprecation", "===", "true", ")", "{", "return", "fn", ";", "}", "const", "msgHandler", "=", "config", ".", "msgHandler", "?", "config", ".", "msgHandler", ":", "defaultMsgHandler", ";", "const", "optionsWarned", "=", "new", "Set", "(", ")", ";", "function", "deprecated", "(", ")", "{", "const", "options", "=", "arguments", "[", "config", ".", "optionsIndex", "]", ";", "// ensure options is a valid, non-empty object, otherwise short-circuit", "if", "(", "!", "isObject", "(", "options", ")", "||", "Object", ".", "keys", "(", "options", ")", ".", "length", "===", "0", ")", "{", "return", "fn", ".", "apply", "(", "this", ",", "arguments", ")", ";", "}", "config", ".", "deprecatedOptions", ".", "forEach", "(", "deprecatedOption", "=>", "{", "if", "(", "options", ".", "hasOwnProperty", "(", "deprecatedOption", ")", "&&", "!", "optionsWarned", ".", "has", "(", "deprecatedOption", ")", ")", "{", "optionsWarned", ".", "add", "(", "deprecatedOption", ")", ";", "const", "msg", "=", "msgHandler", "(", "config", ".", "name", ",", "deprecatedOption", ")", ";", "emitDeprecationWarning", "(", "msg", ")", ";", "if", "(", "this", "&&", "this", ".", "getLogger", ")", "{", "const", "logger", "=", "this", ".", "getLogger", "(", ")", ";", "if", "(", "logger", ")", "{", "logger", ".", "warn", "(", "msg", ")", ";", "}", "}", "}", "}", ")", ";", "return", "fn", ".", "apply", "(", "this", ",", "arguments", ")", ";", "}", "// These lines copied from https://github.com/nodejs/node/blob/25e5ae41688676a5fd29b2e2e7602168eee4ceb5/lib/internal/util.js#L73-L80", "// The wrapper will keep the same prototype as fn to maintain prototype chain", "Object", ".", "setPrototypeOf", "(", "deprecated", ",", "fn", ")", ";", "if", "(", "fn", ".", "prototype", ")", "{", "// Setting this (rather than using Object.setPrototype, as above) ensures", "// that calling the unwrapped constructor gives an instanceof the wrapped", "// constructor.", "deprecated", ".", "prototype", "=", "fn", ".", "prototype", ";", "}", "return", "deprecated", ";", "}" ]
Deprecates a given function's options. @param {object} config configuration for deprecation @param {string} config.name function name @param {Array} config.deprecatedOptions options to deprecate @param {number} config.optionsIndex index of options object in function arguments array @param {function} [config.msgHandler] optional custom message handler to generate warnings @param {function} fn the target function of deprecation @return {function} modified function that warns once per deprecated option, and executes original function @ignore @api private
[ "Deprecates", "a", "given", "function", "s", "options", "." ]
0afbbccf1bd7d437610c33cbd5523f01bc6bc6e5
https://github.com/mongodb/node-mongodb-native/blob/0afbbccf1bd7d437610c33cbd5523f01bc6bc6e5/lib/utils.js#L647-L691
6,489
mongodb/node-mongodb-native
lib/operations/cursor_ops.js
count
function count(cursor, applySkipLimit, opts, callback) { if (applySkipLimit) { if (typeof cursor.cursorSkip() === 'number') opts.skip = cursor.cursorSkip(); if (typeof cursor.cursorLimit() === 'number') opts.limit = cursor.cursorLimit(); } // Ensure we have the right read preference inheritance if (opts.readPreference) { cursor.setReadPreference(opts.readPreference); } if ( typeof opts.maxTimeMS !== 'number' && cursor.s.cmd && typeof cursor.s.cmd.maxTimeMS === 'number' ) { opts.maxTimeMS = cursor.s.cmd.maxTimeMS; } let options = {}; options.skip = opts.skip; options.limit = opts.limit; options.hint = opts.hint; options.maxTimeMS = opts.maxTimeMS; // Command const delimiter = cursor.s.ns.indexOf('.'); options.collectionName = cursor.s.ns.substr(delimiter + 1); let command; try { command = buildCountCommand(cursor, cursor.s.cmd.query, options); } catch (err) { return callback(err); } // Set cursor server to the same as the topology cursor.server = cursor.topology.s.coreTopology; // Execute the command cursor.s.topology.command( `${cursor.s.ns.substr(0, delimiter)}.$cmd`, command, cursor.s.options, (err, result) => { callback(err, result ? result.result.n : null); } ); }
javascript
function count(cursor, applySkipLimit, opts, callback) { if (applySkipLimit) { if (typeof cursor.cursorSkip() === 'number') opts.skip = cursor.cursorSkip(); if (typeof cursor.cursorLimit() === 'number') opts.limit = cursor.cursorLimit(); } // Ensure we have the right read preference inheritance if (opts.readPreference) { cursor.setReadPreference(opts.readPreference); } if ( typeof opts.maxTimeMS !== 'number' && cursor.s.cmd && typeof cursor.s.cmd.maxTimeMS === 'number' ) { opts.maxTimeMS = cursor.s.cmd.maxTimeMS; } let options = {}; options.skip = opts.skip; options.limit = opts.limit; options.hint = opts.hint; options.maxTimeMS = opts.maxTimeMS; // Command const delimiter = cursor.s.ns.indexOf('.'); options.collectionName = cursor.s.ns.substr(delimiter + 1); let command; try { command = buildCountCommand(cursor, cursor.s.cmd.query, options); } catch (err) { return callback(err); } // Set cursor server to the same as the topology cursor.server = cursor.topology.s.coreTopology; // Execute the command cursor.s.topology.command( `${cursor.s.ns.substr(0, delimiter)}.$cmd`, command, cursor.s.options, (err, result) => { callback(err, result ? result.result.n : null); } ); }
[ "function", "count", "(", "cursor", ",", "applySkipLimit", ",", "opts", ",", "callback", ")", "{", "if", "(", "applySkipLimit", ")", "{", "if", "(", "typeof", "cursor", ".", "cursorSkip", "(", ")", "===", "'number'", ")", "opts", ".", "skip", "=", "cursor", ".", "cursorSkip", "(", ")", ";", "if", "(", "typeof", "cursor", ".", "cursorLimit", "(", ")", "===", "'number'", ")", "opts", ".", "limit", "=", "cursor", ".", "cursorLimit", "(", ")", ";", "}", "// Ensure we have the right read preference inheritance", "if", "(", "opts", ".", "readPreference", ")", "{", "cursor", ".", "setReadPreference", "(", "opts", ".", "readPreference", ")", ";", "}", "if", "(", "typeof", "opts", ".", "maxTimeMS", "!==", "'number'", "&&", "cursor", ".", "s", ".", "cmd", "&&", "typeof", "cursor", ".", "s", ".", "cmd", ".", "maxTimeMS", "===", "'number'", ")", "{", "opts", ".", "maxTimeMS", "=", "cursor", ".", "s", ".", "cmd", ".", "maxTimeMS", ";", "}", "let", "options", "=", "{", "}", ";", "options", ".", "skip", "=", "opts", ".", "skip", ";", "options", ".", "limit", "=", "opts", ".", "limit", ";", "options", ".", "hint", "=", "opts", ".", "hint", ";", "options", ".", "maxTimeMS", "=", "opts", ".", "maxTimeMS", ";", "// Command", "const", "delimiter", "=", "cursor", ".", "s", ".", "ns", ".", "indexOf", "(", "'.'", ")", ";", "options", ".", "collectionName", "=", "cursor", ".", "s", ".", "ns", ".", "substr", "(", "delimiter", "+", "1", ")", ";", "let", "command", ";", "try", "{", "command", "=", "buildCountCommand", "(", "cursor", ",", "cursor", ".", "s", ".", "cmd", ".", "query", ",", "options", ")", ";", "}", "catch", "(", "err", ")", "{", "return", "callback", "(", "err", ")", ";", "}", "// Set cursor server to the same as the topology", "cursor", ".", "server", "=", "cursor", ".", "topology", ".", "s", ".", "coreTopology", ";", "// Execute the command", "cursor", ".", "s", ".", "topology", ".", "command", "(", "`", "${", "cursor", ".", "s", ".", "ns", ".", "substr", "(", "0", ",", "delimiter", ")", "}", "`", ",", "command", ",", "cursor", ".", "s", ".", "options", ",", "(", "err", ",", "result", ")", "=>", "{", "callback", "(", "err", ",", "result", "?", "result", ".", "result", ".", "n", ":", "null", ")", ";", "}", ")", ";", "}" ]
Get the count of documents for this cursor. @method @param {Cursor} cursor The Cursor instance on which to count. @param {boolean} [applySkipLimit=true] Specifies whether the count command apply limit and skip settings should be applied on the cursor or in the provided options. @param {object} [options] Optional settings. See Cursor.prototype.count for a list of options. @param {Cursor~countResultCallback} [callback] The result callback.
[ "Get", "the", "count", "of", "documents", "for", "this", "cursor", "." ]
0afbbccf1bd7d437610c33cbd5523f01bc6bc6e5
https://github.com/mongodb/node-mongodb-native/blob/0afbbccf1bd7d437610c33cbd5523f01bc6bc6e5/lib/operations/cursor_ops.js#L26-L74
6,490
mongodb/node-mongodb-native
lib/operations/cursor_ops.js
each
function each(cursor, callback) { let Cursor = loadCursor(); if (!callback) throw MongoError.create({ message: 'callback is mandatory', driver: true }); if (cursor.isNotified()) return; if (cursor.s.state === Cursor.CLOSED || cursor.isDead()) { return handleCallback( callback, MongoError.create({ message: 'Cursor is closed', driver: true }) ); } if (cursor.s.state === Cursor.INIT) cursor.s.state = Cursor.OPEN; // Define function to avoid global scope escape let fn = null; // Trampoline all the entries if (cursor.bufferedCount() > 0) { while ((fn = loop(cursor, callback))) fn(cursor, callback); each(cursor, callback); } else { cursor.next((err, item) => { if (err) return handleCallback(callback, err); if (item == null) { return cursor.close({ skipKillCursors: true }, () => handleCallback(callback, null, null)); } if (handleCallback(callback, null, item) === false) return; each(cursor, callback); }); } }
javascript
function each(cursor, callback) { let Cursor = loadCursor(); if (!callback) throw MongoError.create({ message: 'callback is mandatory', driver: true }); if (cursor.isNotified()) return; if (cursor.s.state === Cursor.CLOSED || cursor.isDead()) { return handleCallback( callback, MongoError.create({ message: 'Cursor is closed', driver: true }) ); } if (cursor.s.state === Cursor.INIT) cursor.s.state = Cursor.OPEN; // Define function to avoid global scope escape let fn = null; // Trampoline all the entries if (cursor.bufferedCount() > 0) { while ((fn = loop(cursor, callback))) fn(cursor, callback); each(cursor, callback); } else { cursor.next((err, item) => { if (err) return handleCallback(callback, err); if (item == null) { return cursor.close({ skipKillCursors: true }, () => handleCallback(callback, null, null)); } if (handleCallback(callback, null, item) === false) return; each(cursor, callback); }); } }
[ "function", "each", "(", "cursor", ",", "callback", ")", "{", "let", "Cursor", "=", "loadCursor", "(", ")", ";", "if", "(", "!", "callback", ")", "throw", "MongoError", ".", "create", "(", "{", "message", ":", "'callback is mandatory'", ",", "driver", ":", "true", "}", ")", ";", "if", "(", "cursor", ".", "isNotified", "(", ")", ")", "return", ";", "if", "(", "cursor", ".", "s", ".", "state", "===", "Cursor", ".", "CLOSED", "||", "cursor", ".", "isDead", "(", ")", ")", "{", "return", "handleCallback", "(", "callback", ",", "MongoError", ".", "create", "(", "{", "message", ":", "'Cursor is closed'", ",", "driver", ":", "true", "}", ")", ")", ";", "}", "if", "(", "cursor", ".", "s", ".", "state", "===", "Cursor", ".", "INIT", ")", "cursor", ".", "s", ".", "state", "=", "Cursor", ".", "OPEN", ";", "// Define function to avoid global scope escape", "let", "fn", "=", "null", ";", "// Trampoline all the entries", "if", "(", "cursor", ".", "bufferedCount", "(", ")", ">", "0", ")", "{", "while", "(", "(", "fn", "=", "loop", "(", "cursor", ",", "callback", ")", ")", ")", "fn", "(", "cursor", ",", "callback", ")", ";", "each", "(", "cursor", ",", "callback", ")", ";", "}", "else", "{", "cursor", ".", "next", "(", "(", "err", ",", "item", ")", "=>", "{", "if", "(", "err", ")", "return", "handleCallback", "(", "callback", ",", "err", ")", ";", "if", "(", "item", "==", "null", ")", "{", "return", "cursor", ".", "close", "(", "{", "skipKillCursors", ":", "true", "}", ",", "(", ")", "=>", "handleCallback", "(", "callback", ",", "null", ",", "null", ")", ")", ";", "}", "if", "(", "handleCallback", "(", "callback", ",", "null", ",", "item", ")", "===", "false", ")", "return", ";", "each", "(", "cursor", ",", "callback", ")", ";", "}", ")", ";", "}", "}" ]
Iterates over all the documents for this cursor. See Cursor.prototype.each for more information. @method @deprecated @param {Cursor} cursor The Cursor instance on which to run. @param {Cursor~resultCallback} callback The result callback.
[ "Iterates", "over", "all", "the", "documents", "for", "this", "cursor", ".", "See", "Cursor", ".", "prototype", ".", "each", "for", "more", "information", "." ]
0afbbccf1bd7d437610c33cbd5523f01bc6bc6e5
https://github.com/mongodb/node-mongodb-native/blob/0afbbccf1bd7d437610c33cbd5523f01bc6bc6e5/lib/operations/cursor_ops.js#L84-L115
6,491
mongodb/node-mongodb-native
lib/operations/cursor_ops.js
next
function next(cursor, callback) { // Return the currentDoc if someone called hasNext first if (cursor.s.currentDoc) { const doc = cursor.s.currentDoc; cursor.s.currentDoc = null; return callback(null, doc); } // Return the next object nextObject(cursor, callback); }
javascript
function next(cursor, callback) { // Return the currentDoc if someone called hasNext first if (cursor.s.currentDoc) { const doc = cursor.s.currentDoc; cursor.s.currentDoc = null; return callback(null, doc); } // Return the next object nextObject(cursor, callback); }
[ "function", "next", "(", "cursor", ",", "callback", ")", "{", "// Return the currentDoc if someone called hasNext first", "if", "(", "cursor", ".", "s", ".", "currentDoc", ")", "{", "const", "doc", "=", "cursor", ".", "s", ".", "currentDoc", ";", "cursor", ".", "s", ".", "currentDoc", "=", "null", ";", "return", "callback", "(", "null", ",", "doc", ")", ";", "}", "// Return the next object", "nextObject", "(", "cursor", ",", "callback", ")", ";", "}" ]
Get the next available document from the cursor. Returns null if no more documents are available. @method @param {Cursor} cursor The Cursor instance from which to get the next document. @param {Cursor~resultCallback} [callback] The result callback.
[ "Get", "the", "next", "available", "document", "from", "the", "cursor", ".", "Returns", "null", "if", "no", "more", "documents", "are", "available", "." ]
0afbbccf1bd7d437610c33cbd5523f01bc6bc6e5
https://github.com/mongodb/node-mongodb-native/blob/0afbbccf1bd7d437610c33cbd5523f01bc6bc6e5/lib/operations/cursor_ops.js#L162-L172
6,492
mongodb/node-mongodb-native
lib/gridfs/chunk.js
function(file, mongoObject, writeConcern) { if (!(this instanceof Chunk)) return new Chunk(file, mongoObject); this.file = file; var mongoObjectFinal = mongoObject == null ? {} : mongoObject; this.writeConcern = writeConcern || { w: 1 }; this.objectId = mongoObjectFinal._id == null ? new ObjectID() : mongoObjectFinal._id; this.chunkNumber = mongoObjectFinal.n == null ? 0 : mongoObjectFinal.n; this.data = new Binary(); if (typeof mongoObjectFinal.data === 'string') { var buffer = Buffer.alloc(mongoObjectFinal.data.length); buffer.write(mongoObjectFinal.data, 0, mongoObjectFinal.data.length, 'binary'); this.data = new Binary(buffer); } else if (Array.isArray(mongoObjectFinal.data)) { buffer = Buffer.alloc(mongoObjectFinal.data.length); var data = mongoObjectFinal.data.join(''); buffer.write(data, 0, data.length, 'binary'); this.data = new Binary(buffer); } else if (mongoObjectFinal.data && mongoObjectFinal.data._bsontype === 'Binary') { this.data = mongoObjectFinal.data; } else if (!Buffer.isBuffer(mongoObjectFinal.data) && !(mongoObjectFinal.data == null)) { throw Error('Illegal chunk format'); } // Update position this.internalPosition = 0; }
javascript
function(file, mongoObject, writeConcern) { if (!(this instanceof Chunk)) return new Chunk(file, mongoObject); this.file = file; var mongoObjectFinal = mongoObject == null ? {} : mongoObject; this.writeConcern = writeConcern || { w: 1 }; this.objectId = mongoObjectFinal._id == null ? new ObjectID() : mongoObjectFinal._id; this.chunkNumber = mongoObjectFinal.n == null ? 0 : mongoObjectFinal.n; this.data = new Binary(); if (typeof mongoObjectFinal.data === 'string') { var buffer = Buffer.alloc(mongoObjectFinal.data.length); buffer.write(mongoObjectFinal.data, 0, mongoObjectFinal.data.length, 'binary'); this.data = new Binary(buffer); } else if (Array.isArray(mongoObjectFinal.data)) { buffer = Buffer.alloc(mongoObjectFinal.data.length); var data = mongoObjectFinal.data.join(''); buffer.write(data, 0, data.length, 'binary'); this.data = new Binary(buffer); } else if (mongoObjectFinal.data && mongoObjectFinal.data._bsontype === 'Binary') { this.data = mongoObjectFinal.data; } else if (!Buffer.isBuffer(mongoObjectFinal.data) && !(mongoObjectFinal.data == null)) { throw Error('Illegal chunk format'); } // Update position this.internalPosition = 0; }
[ "function", "(", "file", ",", "mongoObject", ",", "writeConcern", ")", "{", "if", "(", "!", "(", "this", "instanceof", "Chunk", ")", ")", "return", "new", "Chunk", "(", "file", ",", "mongoObject", ")", ";", "this", ".", "file", "=", "file", ";", "var", "mongoObjectFinal", "=", "mongoObject", "==", "null", "?", "{", "}", ":", "mongoObject", ";", "this", ".", "writeConcern", "=", "writeConcern", "||", "{", "w", ":", "1", "}", ";", "this", ".", "objectId", "=", "mongoObjectFinal", ".", "_id", "==", "null", "?", "new", "ObjectID", "(", ")", ":", "mongoObjectFinal", ".", "_id", ";", "this", ".", "chunkNumber", "=", "mongoObjectFinal", ".", "n", "==", "null", "?", "0", ":", "mongoObjectFinal", ".", "n", ";", "this", ".", "data", "=", "new", "Binary", "(", ")", ";", "if", "(", "typeof", "mongoObjectFinal", ".", "data", "===", "'string'", ")", "{", "var", "buffer", "=", "Buffer", ".", "alloc", "(", "mongoObjectFinal", ".", "data", ".", "length", ")", ";", "buffer", ".", "write", "(", "mongoObjectFinal", ".", "data", ",", "0", ",", "mongoObjectFinal", ".", "data", ".", "length", ",", "'binary'", ")", ";", "this", ".", "data", "=", "new", "Binary", "(", "buffer", ")", ";", "}", "else", "if", "(", "Array", ".", "isArray", "(", "mongoObjectFinal", ".", "data", ")", ")", "{", "buffer", "=", "Buffer", ".", "alloc", "(", "mongoObjectFinal", ".", "data", ".", "length", ")", ";", "var", "data", "=", "mongoObjectFinal", ".", "data", ".", "join", "(", "''", ")", ";", "buffer", ".", "write", "(", "data", ",", "0", ",", "data", ".", "length", ",", "'binary'", ")", ";", "this", ".", "data", "=", "new", "Binary", "(", "buffer", ")", ";", "}", "else", "if", "(", "mongoObjectFinal", ".", "data", "&&", "mongoObjectFinal", ".", "data", ".", "_bsontype", "===", "'Binary'", ")", "{", "this", ".", "data", "=", "mongoObjectFinal", ".", "data", ";", "}", "else", "if", "(", "!", "Buffer", ".", "isBuffer", "(", "mongoObjectFinal", ".", "data", ")", "&&", "!", "(", "mongoObjectFinal", ".", "data", "==", "null", ")", ")", "{", "throw", "Error", "(", "'Illegal chunk format'", ")", ";", "}", "// Update position", "this", ".", "internalPosition", "=", "0", ";", "}" ]
Class for representing a single chunk in GridFS. @class @param file {GridStore} The {@link GridStore} object holding this chunk. @param mongoObject {object} The mongo object representation of this chunk. @throws Error when the type of data field for {@link mongoObject} is not supported. Currently supported types for data field are instances of {@link String}, {@link Array}, {@link Binary} and {@link Binary} from the bson module @see Chunk#buildMongoObject
[ "Class", "for", "representing", "a", "single", "chunk", "in", "GridFS", "." ]
0afbbccf1bd7d437610c33cbd5523f01bc6bc6e5
https://github.com/mongodb/node-mongodb-native/blob/0afbbccf1bd7d437610c33cbd5523f01bc6bc6e5/lib/gridfs/chunk.js#L23-L50
6,493
mongodb/node-mongodb-native
lib/command_cursor.js
function(bson, ns, cmd, options, topology, topologyOptions) { CoreCursor.apply(this, Array.prototype.slice.call(arguments, 0)); var state = CommandCursor.INIT; var streamOptions = {}; // MaxTimeMS var maxTimeMS = null; // Get the promiseLibrary var promiseLibrary = options.promiseLibrary || Promise; // Set up Readable.call(this, { objectMode: true }); // Internal state this.s = { // MaxTimeMS maxTimeMS: maxTimeMS, // State state: state, // Stream options streamOptions: streamOptions, // BSON bson: bson, // Namespace ns: ns, // Command cmd: cmd, // Options options: options, // Topology topology: topology, // Topology Options topologyOptions: topologyOptions, // Promise library promiseLibrary: promiseLibrary, // Optional ClientSession session: options.session }; }
javascript
function(bson, ns, cmd, options, topology, topologyOptions) { CoreCursor.apply(this, Array.prototype.slice.call(arguments, 0)); var state = CommandCursor.INIT; var streamOptions = {}; // MaxTimeMS var maxTimeMS = null; // Get the promiseLibrary var promiseLibrary = options.promiseLibrary || Promise; // Set up Readable.call(this, { objectMode: true }); // Internal state this.s = { // MaxTimeMS maxTimeMS: maxTimeMS, // State state: state, // Stream options streamOptions: streamOptions, // BSON bson: bson, // Namespace ns: ns, // Command cmd: cmd, // Options options: options, // Topology topology: topology, // Topology Options topologyOptions: topologyOptions, // Promise library promiseLibrary: promiseLibrary, // Optional ClientSession session: options.session }; }
[ "function", "(", "bson", ",", "ns", ",", "cmd", ",", "options", ",", "topology", ",", "topologyOptions", ")", "{", "CoreCursor", ".", "apply", "(", "this", ",", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "arguments", ",", "0", ")", ")", ";", "var", "state", "=", "CommandCursor", ".", "INIT", ";", "var", "streamOptions", "=", "{", "}", ";", "// MaxTimeMS", "var", "maxTimeMS", "=", "null", ";", "// Get the promiseLibrary", "var", "promiseLibrary", "=", "options", ".", "promiseLibrary", "||", "Promise", ";", "// Set up", "Readable", ".", "call", "(", "this", ",", "{", "objectMode", ":", "true", "}", ")", ";", "// Internal state", "this", ".", "s", "=", "{", "// MaxTimeMS", "maxTimeMS", ":", "maxTimeMS", ",", "// State", "state", ":", "state", ",", "// Stream options", "streamOptions", ":", "streamOptions", ",", "// BSON", "bson", ":", "bson", ",", "// Namespace", "ns", ":", "ns", ",", "// Command", "cmd", ":", "cmd", ",", "// Options", "options", ":", "options", ",", "// Topology", "topology", ":", "topology", ",", "// Topology Options", "topologyOptions", ":", "topologyOptions", ",", "// Promise library", "promiseLibrary", ":", "promiseLibrary", ",", "// Optional ClientSession", "session", ":", "options", ".", "session", "}", ";", "}" ]
Namespace provided by the browser. @external Readable Creates a new Command Cursor instance (INTERNAL TYPE, do not instantiate directly) @class CommandCursor @extends external:Readable @fires CommandCursor#data @fires CommandCursor#end @fires CommandCursor#close @fires CommandCursor#readable @return {CommandCursor} an CommandCursor instance.
[ "Namespace", "provided", "by", "the", "browser", "." ]
0afbbccf1bd7d437610c33cbd5523f01bc6bc6e5
https://github.com/mongodb/node-mongodb-native/blob/0afbbccf1bd7d437610c33cbd5523f01bc6bc6e5/lib/command_cursor.js#L57-L96
6,494
mongodb/node-mongodb-native
lib/gridfs/grid_store.js
function(self, callback) { // Calcuate the length var mongoObject = { _id: self.fileId, filename: self.filename, contentType: self.contentType, length: self.position ? self.position : 0, chunkSize: self.chunkSize, uploadDate: self.uploadDate, aliases: self.aliases, metadata: self.metadata }; var md5Command = { filemd5: self.fileId, root: self.root }; self.db.command(md5Command, function(err, results) { if (err) return callback(err); mongoObject.md5 = results.md5; callback(null, mongoObject); }); }
javascript
function(self, callback) { // Calcuate the length var mongoObject = { _id: self.fileId, filename: self.filename, contentType: self.contentType, length: self.position ? self.position : 0, chunkSize: self.chunkSize, uploadDate: self.uploadDate, aliases: self.aliases, metadata: self.metadata }; var md5Command = { filemd5: self.fileId, root: self.root }; self.db.command(md5Command, function(err, results) { if (err) return callback(err); mongoObject.md5 = results.md5; callback(null, mongoObject); }); }
[ "function", "(", "self", ",", "callback", ")", "{", "// Calcuate the length", "var", "mongoObject", "=", "{", "_id", ":", "self", ".", "fileId", ",", "filename", ":", "self", ".", "filename", ",", "contentType", ":", "self", ".", "contentType", ",", "length", ":", "self", ".", "position", "?", "self", ".", "position", ":", "0", ",", "chunkSize", ":", "self", ".", "chunkSize", ",", "uploadDate", ":", "self", ".", "uploadDate", ",", "aliases", ":", "self", ".", "aliases", ",", "metadata", ":", "self", ".", "metadata", "}", ";", "var", "md5Command", "=", "{", "filemd5", ":", "self", ".", "fileId", ",", "root", ":", "self", ".", "root", "}", ";", "self", ".", "db", ".", "command", "(", "md5Command", ",", "function", "(", "err", ",", "results", ")", "{", "if", "(", "err", ")", "return", "callback", "(", "err", ")", ";", "mongoObject", ".", "md5", "=", "results", ".", "md5", ";", "callback", "(", "null", ",", "mongoObject", ")", ";", "}", ")", ";", "}" ]
Creates a mongoDB object representation of this object. <pre><code> { '_id' : , // {number} id for this file 'filename' : , // {string} name for this file 'contentType' : , // {string} mime type for this file 'length' : , // {number} size of this file? 'chunksize' : , // {number} chunk size used by this file 'uploadDate' : , // {Date} 'aliases' : , // {array of string} 'metadata' : , // {string} } </code></pre> @ignore
[ "Creates", "a", "mongoDB", "object", "representation", "of", "this", "object", "." ]
0afbbccf1bd7d437610c33cbd5523f01bc6bc6e5
https://github.com/mongodb/node-mongodb-native/blob/0afbbccf1bd7d437610c33cbd5523f01bc6bc6e5/lib/gridfs/grid_store.js#L1155-L1175
6,495
mongodb/node-mongodb-native
lib/gridfs/grid_store.js
function(self, chunkNumber, options, callback) { if (typeof options === 'function') { callback = options; options = {}; } options = options || self.writeConcern; options.readPreference = self.readPreference; // Get the nth chunk self .chunkCollection() .findOne({ files_id: self.fileId, n: chunkNumber }, options, function(err, chunk) { if (err) return callback(err); var finalChunk = chunk == null ? {} : chunk; callback(null, new Chunk(self, finalChunk, self.writeConcern)); }); }
javascript
function(self, chunkNumber, options, callback) { if (typeof options === 'function') { callback = options; options = {}; } options = options || self.writeConcern; options.readPreference = self.readPreference; // Get the nth chunk self .chunkCollection() .findOne({ files_id: self.fileId, n: chunkNumber }, options, function(err, chunk) { if (err) return callback(err); var finalChunk = chunk == null ? {} : chunk; callback(null, new Chunk(self, finalChunk, self.writeConcern)); }); }
[ "function", "(", "self", ",", "chunkNumber", ",", "options", ",", "callback", ")", "{", "if", "(", "typeof", "options", "===", "'function'", ")", "{", "callback", "=", "options", ";", "options", "=", "{", "}", ";", "}", "options", "=", "options", "||", "self", ".", "writeConcern", ";", "options", ".", "readPreference", "=", "self", ".", "readPreference", ";", "// Get the nth chunk", "self", ".", "chunkCollection", "(", ")", ".", "findOne", "(", "{", "files_id", ":", "self", ".", "fileId", ",", "n", ":", "chunkNumber", "}", ",", "options", ",", "function", "(", "err", ",", "chunk", ")", "{", "if", "(", "err", ")", "return", "callback", "(", "err", ")", ";", "var", "finalChunk", "=", "chunk", "==", "null", "?", "{", "}", ":", "chunk", ";", "callback", "(", "null", ",", "new", "Chunk", "(", "self", ",", "finalChunk", ",", "self", ".", "writeConcern", ")", ")", ";", "}", ")", ";", "}" ]
Gets the nth chunk of this file. @ignore
[ "Gets", "the", "nth", "chunk", "of", "this", "file", "." ]
0afbbccf1bd7d437610c33cbd5523f01bc6bc6e5
https://github.com/mongodb/node-mongodb-native/blob/0afbbccf1bd7d437610c33cbd5523f01bc6bc6e5/lib/gridfs/grid_store.js#L1181-L1198
6,496
mongodb/node-mongodb-native
lib/gridfs/grid_store.js
function(self, options, callback) { if (typeof options === 'function') { callback = options; options = {}; } options = options || self.writeConcern; if (self.fileId != null) { self.chunkCollection().remove({ files_id: self.fileId }, options, function(err) { if (err) return callback(err, false); callback(null, true); }); } else { callback(null, true); } }
javascript
function(self, options, callback) { if (typeof options === 'function') { callback = options; options = {}; } options = options || self.writeConcern; if (self.fileId != null) { self.chunkCollection().remove({ files_id: self.fileId }, options, function(err) { if (err) return callback(err, false); callback(null, true); }); } else { callback(null, true); } }
[ "function", "(", "self", ",", "options", ",", "callback", ")", "{", "if", "(", "typeof", "options", "===", "'function'", ")", "{", "callback", "=", "options", ";", "options", "=", "{", "}", ";", "}", "options", "=", "options", "||", "self", ".", "writeConcern", ";", "if", "(", "self", ".", "fileId", "!=", "null", ")", "{", "self", ".", "chunkCollection", "(", ")", ".", "remove", "(", "{", "files_id", ":", "self", ".", "fileId", "}", ",", "options", ",", "function", "(", "err", ")", "{", "if", "(", "err", ")", "return", "callback", "(", "err", ",", "false", ")", ";", "callback", "(", "null", ",", "true", ")", ";", "}", ")", ";", "}", "else", "{", "callback", "(", "null", ",", "true", ")", ";", "}", "}" ]
Deletes all the chunks of this file in the database. @ignore
[ "Deletes", "all", "the", "chunks", "of", "this", "file", "in", "the", "database", "." ]
0afbbccf1bd7d437610c33cbd5523f01bc6bc6e5
https://github.com/mongodb/node-mongodb-native/blob/0afbbccf1bd7d437610c33cbd5523f01bc6bc6e5/lib/gridfs/grid_store.js#L1212-L1228
6,497
mongodb/node-mongodb-native
lib/gridfs-stream/download.js
GridFSBucketReadStream
function GridFSBucketReadStream(chunks, files, readPreference, filter, options) { this.s = { bytesRead: 0, chunks: chunks, cursor: null, expected: 0, files: files, filter: filter, init: false, expectedEnd: 0, file: null, options: options, readPreference: readPreference }; stream.Readable.call(this); }
javascript
function GridFSBucketReadStream(chunks, files, readPreference, filter, options) { this.s = { bytesRead: 0, chunks: chunks, cursor: null, expected: 0, files: files, filter: filter, init: false, expectedEnd: 0, file: null, options: options, readPreference: readPreference }; stream.Readable.call(this); }
[ "function", "GridFSBucketReadStream", "(", "chunks", ",", "files", ",", "readPreference", ",", "filter", ",", "options", ")", "{", "this", ".", "s", "=", "{", "bytesRead", ":", "0", ",", "chunks", ":", "chunks", ",", "cursor", ":", "null", ",", "expected", ":", "0", ",", "files", ":", "files", ",", "filter", ":", "filter", ",", "init", ":", "false", ",", "expectedEnd", ":", "0", ",", "file", ":", "null", ",", "options", ":", "options", ",", "readPreference", ":", "readPreference", "}", ";", "stream", ".", "Readable", ".", "call", "(", "this", ")", ";", "}" ]
A readable stream that enables you to read buffers from GridFS. Do not instantiate this class directly. Use `openDownloadStream()` instead. @class @param {Collection} chunks Handle for chunks collection @param {Collection} files Handle for files collection @param {Object} readPreference The read preference to use @param {Object} filter The query to use to find the file document @param {Object} [options] Optional settings. @param {Number} [options.sort] Optional sort for the file find query @param {Number} [options.skip] Optional skip for the file find query @param {Number} [options.start] Optional 0-based offset in bytes to start streaming from @param {Number} [options.end] Optional 0-based offset in bytes to stop streaming before @fires GridFSBucketReadStream#error @fires GridFSBucketReadStream#file @return {GridFSBucketReadStream} a GridFSBucketReadStream instance.
[ "A", "readable", "stream", "that", "enables", "you", "to", "read", "buffers", "from", "GridFS", "." ]
0afbbccf1bd7d437610c33cbd5523f01bc6bc6e5
https://github.com/mongodb/node-mongodb-native/blob/0afbbccf1bd7d437610c33cbd5523f01bc6bc6e5/lib/gridfs-stream/download.js#L28-L44
6,498
mongodb/node-mongodb-native
lib/operations/admin_ops.js
replSetGetStatus
function replSetGetStatus(admin, options, callback) { executeDbAdminCommand(admin.s.db, { replSetGetStatus: 1 }, options, callback); }
javascript
function replSetGetStatus(admin, options, callback) { executeDbAdminCommand(admin.s.db, { replSetGetStatus: 1 }, options, callback); }
[ "function", "replSetGetStatus", "(", "admin", ",", "options", ",", "callback", ")", "{", "executeDbAdminCommand", "(", "admin", ".", "s", ".", "db", ",", "{", "replSetGetStatus", ":", "1", "}", ",", "options", ",", "callback", ")", ";", "}" ]
Get ReplicaSet status @param {Admin} a collection instance. @param {Object} [options] Optional settings. See Admin.prototype.replSetGetStatus for a list of options. @param {Admin~resultCallback} [callback] The command result callback.
[ "Get", "ReplicaSet", "status" ]
0afbbccf1bd7d437610c33cbd5523f01bc6bc6e5
https://github.com/mongodb/node-mongodb-native/blob/0afbbccf1bd7d437610c33cbd5523f01bc6bc6e5/lib/operations/admin_ops.js#L13-L15
6,499
mongodb/node-mongodb-native
lib/operations/admin_ops.js
serverStatus
function serverStatus(admin, options, callback) { executeDbAdminCommand(admin.s.db, { serverStatus: 1 }, options, callback); }
javascript
function serverStatus(admin, options, callback) { executeDbAdminCommand(admin.s.db, { serverStatus: 1 }, options, callback); }
[ "function", "serverStatus", "(", "admin", ",", "options", ",", "callback", ")", "{", "executeDbAdminCommand", "(", "admin", ".", "s", ".", "db", ",", "{", "serverStatus", ":", "1", "}", ",", "options", ",", "callback", ")", ";", "}" ]
Retrieve this db's server status. @param {Admin} a collection instance. @param {Object} [options] Optional settings. See Admin.prototype.serverStatus for a list of options. @param {Admin~resultCallback} [callback] The command result callback
[ "Retrieve", "this", "db", "s", "server", "status", "." ]
0afbbccf1bd7d437610c33cbd5523f01bc6bc6e5
https://github.com/mongodb/node-mongodb-native/blob/0afbbccf1bd7d437610c33cbd5523f01bc6bc6e5/lib/operations/admin_ops.js#L24-L26