I
I
Ivan Tabakerka2018-10-25 04:04:01
MongoDB
Ivan Tabakerka, 2018-10-25 04:04:01

How to return data from MongoDB using Mongoose?

There is such a code. It searches the database for login matches in the users table.

const controllerCheckInput = (value) => {
  let result = users.find({login: value}, function (err, docs) {
    if (err) console.log(err)
    let result = ''
    if (docs == ''){
      result = true // Совпадений нет, можно продолжать регистрацию
    } else {
      result = false // Найдено совпадение, регистрация невозможна
    }
    return result // Вот тут как раз и не ясно, как вывести переменную из функции find
  })
  console.log(result)
}
// Результат:
Query {
  _mongooseOptions: {},
  _transforms: [],
  mongooseCollection:
   NativeCollection {
     collection: Collection { s: [Object] },
     opts:
      { bufferCommands: true,
        capped: false,
        '$wasForceClosed': undefined },
     name: 'users',
     collectionName: 'users',
     conn:
      NativeConnection {
        base: [Mongoose],
        collections: [Object],
        models: [Object],
        config: [Object],
        replica: false,
        options: null,
        otherDbs: [],
        relatedDbs: {},
        states: [Object],
        _readyState: 1,
        _closeCalled: false,
        _hasOpened: true,
        '$internalEmitter': [EventEmitter],
        _listening: false,
        _connectionOptions: [Object],
        name: 'magnolia',
        host: 'localhost',
        port: 27017,
        user: null,
        pass: null,
        client: [MongoClient],
        '$initialConnection': [Promise],
        db: [Db] },
     queue: [],
     buffer: false,
     emitter:
      EventEmitter { _events: {}, _eventsCount: 0, _maxListeners: undefined } },
  model:
   { [Function: model]
     hooks: Kareem { _pres: [Map], _posts: [Map] },
     base:
      Mongoose {
        connections: [Array],
        models: [Object],
        modelSchemas: [Object],
        options: [Object],
        _pluralize: [Function: pluralize],
        plugins: [Array] },
     modelName: 'users',
     model: [Function: model],
     db:
      NativeConnection {
        base: [Mongoose],
        collections: [Object],
        models: [Object],
        config: [Object],
        replica: false,
        options: null,
        otherDbs: [],
        relatedDbs: {},
        states: [Object],
        _readyState: 1,
        _closeCalled: false,
        _hasOpened: true,
        '$internalEmitter': [EventEmitter],
        _listening: false,
        _connectionOptions: [Object],
        name: 'magnolia',
        host: 'localhost',
        port: 27017,
        user: null,
        pass: null,
        client: [MongoClient],
        '$initialConnection': [Promise],
        db: [Db] },
     discriminators: undefined,
     '$appliedMethods': true,
     '$appliedHooks': true,
     schema:
      Schema {
        obj: [Object],
        paths: [Object],
        aliases: {},
        subpaths: {},
        virtuals: [Object],
        singleNestedPaths: {},
        nested: {},
        inherits: {},
        callQueue: [],
        _indexes: [],
        methods: {},
        methodOptions: {},
        statics: {},
        tree: [Object],
        query: {},
        childSchemas: [],
        plugins: [Array],
        '$id': 1,
        s: [Object],
        _userProvidedOptions: {},
        options: [Object],
        '$globalPluginsApplied': true },
     collection:
      NativeCollection {
        collection: [Collection],
        opts: [Object],
        name: 'users',
        collectionName: 'users',
        conn: [NativeConnection],
        queue: [],
        buffer: false,
        emitter: [EventEmitter] },
     Query: { [Function] base: [Query] },
     '$__insertMany': [Function],
     '$init': Promise { [Circular] },
     '$caught': true },
  schema:
   Schema {
     obj:
      { _id: [Function],
        login: [Function: String],
        email: [Function: String],
        password: [Function: String],
        group: [Function: Number],
        created: [Object] },
     paths:
      { _id: [ObjectId],
        login: [SchemaString],
        email: [SchemaString],
        password: [SchemaString],
        group: [SchemaNumber],
        created: [SchemaDate],
        __v: [SchemaNumber] },
     aliases: {},
     subpaths: {},
     virtuals: { id: [VirtualType] },
     singleNestedPaths: {},
     nested: {},
     inherits: {},
     callQueue: [],
     _indexes: [],
     methods: {},
     methodOptions: {},
     statics: {},
     tree:
      { _id: [Function],
        login: [Function: String],
        email: [Function: String],
        password: [Function: String],
        group: [Function: Number],
        created: [Object],
        __v: [Function: Number],
        id: [VirtualType] },
     query: {},
     childSchemas: [],
     plugins: [ [Object], [Object], [Object], [Object], [Object] ],
     '$id': 1,
     s: { hooks: [Kareem] },
     _userProvidedOptions: {},
     options:
      { typeKey: 'type',
        id: true,
        noVirtualId: false,
        _id: true,
        noId: false,
        validateBeforeSave: true,
        read: null,
        shardKey: null,
        autoIndex: null,
        minimize: true,
        discriminatorKey: '__t',
        versionKey: '__v',
        capped: false,
        bufferCommands: true,
        strict: true,
        pluralization: true },
     '$globalPluginsApplied': true },
  op: 'find',
  options: {},
  _conditions: { login: '1122' },
  _fields: undefined,
  _update: undefined,
  _path: undefined,
  _distinct: undefined,
  _collection:
   NodeCollection {
     collection:
      NativeCollection {
        collection: [Collection],
        opts: [Object],
        name: 'users',
        collectionName: 'users',
        conn: [NativeConnection],
        queue: [],
        buffer: false,
        emitter: [EventEmitter] },
     collectionName: 'users' },
  _traceFunction: undefined,
  '$useProjection': true }

In all the manuals that I found, they usually display data from the database through console.log (). I also have them displayed in the console, BUT YOKARNY BABAI, HOW TO DISPLAY THEM INTO A VARIABLE AND USE IN THE CODE!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Ilya Gerasimov, 2018-10-25
@IvanTabakerka

const controllerCheckInput = value =>
    users.find({ login: value }).then(res => !!res);

  // вариант async/await
  (async () => {
    const exists = await controllerCheckInput('login');
    console.log(exists);
  })();

  // then/catch
  (() => {
    controllerCheckInput('login').then(exists => {
      console.log(exists);
    });
  })();

  // примерно так это выглядит в express
  app.post('/register', async (req, res) => {
    const exists = await controllerCheckInput('login');
    console.log(exists);
  });

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question