IvanTabakerka
@IvanTabakerka
Чистокровный говнокодер

Как вернуть данные из MongoDB с использованием Mongoose?

Есть вот такой код. Он ищет в базе данных совпадения логина в таблице users.
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 }

Во всех мануалах которых я находил, обычно выводят данные из базы через console.log(). У меня тоже они в консоль выводятся, НО ЁКАРНЫЙ БАБАЙ, КАК ВЫВЕСТИ ИХ В ПЕРЕМЕННУЮ И ИСПОЛЬЗОВАТЬ В КОДЕ!
  • Вопрос задан
  • 899 просмотров
Решения вопроса 2
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);
  });
Ответ написан
IvanTabakerka
@IvanTabakerka Автор вопроса
Чистокровный говнокодер
Функция для выбивания данных из MongoDB:
function controlCheckInput(value, callback) {
  users.findOne({login: value}).exec((err, doc) => {
    if (err) console.log(err)
    if (doc == null) {
      callback(true)
    } else {
      callback(false)
    }
  })
}

Получение результата:
controlCheckInput('user', function (result) {
    console.log(result)
})


Восьмичасовое насилие редактора окончено
Ответ написан
Комментировать
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы
19 апр. 2024, в 11:14
65000 руб./за проект
19 апр. 2024, в 11:08
5000 руб./за проект
19 апр. 2024, в 10:59
150000 руб./за проект