Как искать все документы, содержащие ключевое слово, в MongoDB - PullRequest
0 голосов
/ 27 мая 2020

Я играю со встроенным поиском Mon go DB на основе текстовых индексов, и я просто хочу вернуть все документы, содержащие ключевое слово, которое я искал, он работает, но вместо этого дает мне следующий результат:

Cursor {
  pool: null,
  server: null,
  disconnectHandler: Store {
    s: { storedOps: [], storeOptions: [Object], topology: [Server] },
    length: [Getter]
  },
  bson: BSON {},
  ns: 'heroku_hc9xjmcl.posts_with_tags_test',
  cmd: {
    find: 'heroku_hc9xjmcl.posts_with_tags_test',
    limit: 0,
    skip: 0,
    query: { '$text': [Object] },
    raw: undefined,
    hint: null,
    timeout: undefined,
    slaveOk: false,
    readPreference: null
  },
  options: {
    skip: 0,
    limit: 0,
    raw: undefined,
    hint: null,
    timeout: undefined,
    slaveOk: false,
    readPreference: null,
    db: Db {
      _events: [Object: null prototype],
      _eventsCount: 3,
      _maxListeners: undefined,
      s: [Object],
      serverConfig: [Getter],
      bufferMaxEntries: [Getter],
      databaseName: [Getter],
      [Symbol(kCapture)]: false
    },
    promiseLibrary: [Function: Promise],
    disconnectHandler: Store { s: [Object], length: [Getter] },
    topology: Server {
      _events: [Object: null prototype],
      _eventsCount: 26,
      _maxListeners: Infinity,
      clientInfo: [Object],
      s: [Object],
      [Symbol(kCapture)]: false
    }
  },
  topology: Server {
    _events: [Object: null prototype] {
      serverOpening: [Function (anonymous)],
      serverDescriptionChanged: [Function (anonymous)],
      serverHeartbeatStarted: [Function (anonymous)],
      serverHeartbeatSucceeded: [Function (anonymous)],
      serverHeartbeatFailed: [Function (anonymous)],
      serverClosed: [Function (anonymous)],
      topologyOpening: [Function (anonymous)],
      topologyClosed: [Function (anonymous)],
      topologyDescriptionChanged: [Function (anonymous)],
      commandStarted: [Function (anonymous)],
      commandSucceeded: [Function (anonymous)],
      commandFailed: [Function (anonymous)],
      joined: [Array],
      left: [Array],
      ping: [Function (anonymous)],
      ha: [Function (anonymous)],
      authenticated: [Function (anonymous)],
      error: [Array],
      timeout: [Array],
      close: [Array],
      parseError: [Array],
      open: [Array],
      fullsetup: [Array],
      all: [Array],
      reconnect: [Array],
      reconnectFailed: [Function (anonymous)]
    },
    _eventsCount: 26,
    _maxListeners: Infinity,
    clientInfo: { driver: [Object], os: [Object], platform: 'Node.js v13.6.0, LE' },
    s: {
      coreTopology: [Server],
      sCapabilities: [ServerCapabilities],
      clonedOptions: [Object],
      reconnect: true,
      emitError: true,
      poolSize: 5,
      storeOptions: [Object],
      store: [Store],
      host: 'ds241968.mlab.com',
      port: 41968,
      options: [Object],
      sessionPool: [ServerSessionPool],
      sessions: [Array],
      promiseLibrary: [Function: Promise]
    },
    [Symbol(kCapture)]: false
  },
  cursorState: {
    cursorId: null,
    cmd: {
      find: 'heroku_hc9xjmcl.posts_with_tags_test',
      limit: 0,
      skip: 0,
      query: [Object],
      raw: undefined,
      hint: null,
      timeout: undefined,
      slaveOk: false,
      readPreference: null
    },
    documents: [],
    cursorIndex: 0,
    dead: false,
    killed: false,
    init: false,
    notified: false,
    limit: 0,
    skip: 0,
    batchSize: 1000,
    currentLimit: 0,
    transforms: undefined,
    raw: undefined,
    reconnect: true
  },
  logger: Logger { className: 'Cursor' },
  _readableState: ReadableState {
    objectMode: true,
    highWaterMark: 16,
    buffer: BufferList { head: null, tail: null, length: 0 },
    length: 0,
    pipes: [],
    flowing: null,
    ended: false,
    endEmitted: false,
    reading: false,
    sync: true,
    needReadable: false,
    emittedReadable: false,
    readableListening: false,
    resumeScheduled: false,
    errorEmitted: false,
    emitClose: true,
    autoDestroy: false,
    destroyed: false,
    defaultEncoding: 'utf8',
    awaitDrainWriters: null,
    multiAwaitDrain: false,
    readingMore: false,
    decoder: null,
    encoding: null,
    [Symbol(kPaused)]: null
  },
  readable: true,
  _events: [Object: null prototype] {},
  _eventsCount: 0,
  _maxListeners: undefined,
  s: {
    numberOfRetries: 5,
    tailableRetryInterval: 500,
    currentNumberOfRetries: 5,
    state: 0,
    streamOptions: {},
    bson: BSON {},
    ns: 'heroku_hc9xjmcl.posts_with_tags_test',
    cmd: {
      find: 'heroku_hc9xjmcl.posts_with_tags_test',
      limit: 0,
      skip: 0,
      query: [Object],
      raw: undefined,
      hint: null,
      timeout: undefined,
      slaveOk: false,
      readPreference: null
    },
    options: {
      skip: 0,
      limit: 0,
      raw: undefined,
      hint: null,
      timeout: undefined,
      slaveOk: false,
      readPreference: null,
      db: [Db],
      promiseLibrary: [Function: Promise],
      disconnectHandler: [Store],
      topology: [Server]
    },
    topology: Server {
      _events: [Object: null prototype],
      _eventsCount: 26,
      _maxListeners: Infinity,
      clientInfo: [Object],
      s: [Object],
      [Symbol(kCapture)]: false
    },
    topologyOptions: {
      host: 'ds241968.mlab.com',
      port: 41968,
      disconnectHandler: [Store],
      cursorFactory: [Function],
      reconnect: true,
      emitError: true,
      size: 5,
      monitorCommands: false,
      promiseLibrary: [Function: Promise],
      socketTimeout: 360000,
      connectionTimeout: 30000,
      clientInfo: [Object],
      servers: [Array],
      caseTranslate: true,
      useNewUrlParser: true,
      auth: [Object],
      authSource: 'heroku_hc9xjmcl',
      dbName: 'heroku_hc9xjmcl',
      socketTimeoutMS: 360000,
      connectTimeoutMS: 30000,
      credentials: [MongoCredentials],
      bson: BSON {}
    },
    promiseLibrary: [Function: Promise],
    currentDoc: null,
    explicitlyIgnoreSession: undefined
  },
  sortValue: undefined,
  [Symbol(kCapture)]: false
}

Как я могу получить вывод, который просто возвращает документы в моей базе данных, содержащие поисковый запрос? Вот мой соответствующий код:

const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const cors = require('cors');
require('dotenv').config();
const mongoose = require('mongoose');
const PORT = process.env.PORT || 3001;
const BASE_URL = PROCESS.ENV.BASE_URL;
const itemRoutes = express.Router();

app.use(cors());
app.use(bodyParser.json());

mongoose.connect(BASE_URL, { useNewUrlParser: true })

const connection = mongoose.connection;

connection.once('open', function () {
  console.log('Connection to MongoDB established succesfully!');
});

let collection = connection.collection("posts_with_tags_test");
collection.createIndex({ postContent: 'text' });

// Serve static assets
if (process.env.NODE_ENV === 'production') {
  app.use(express.static('build'));
}

itemRoutes.route('/search').get(async (req, res) => {
  connection.collection("posts_with_tags_test").createIndex({ postContent: "text" })
  let result = await connection.collection("posts_with_tags_test").find({
    $text: {
      $search: "culpa aliquid"
    }
  })
  console.log(result);
});

app.use('/search', itemRoutes);

app.listen(PORT, function () {
  console.log('Server is running on' + ' ' + PORT);
})

1 Ответ

1 голос
/ 27 мая 2020

db.collection.find возвращает Cursor, который является указателем на набор результатов запроса, для доступа к результату вы можете использовать db.collection.find ({}). ToArray () для возврата массива документов или

.forEach(function(item){
// and you can print or do what you want with each item
})

в вашем случае думаю console.log(result.toArray()); достаточно

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...