A
A
Anton Ulanov2017-04-14 19:40:58
MongoDB
Anton Ulanov, 2017-04-14 19:40:58

How to get all records from database in mongodb on nodejs?

Good afternoon, I decided to write a simple website for myself and at the same time finally start learning JS. For the task I took to write a small rest api service for myself. I'm writing by manu,
there was a question in mana, there are operations for getting a record by id, updating a record by id, deleting a record, but there is no getting all the records. Tried to get all records by calling

router.get('/birdss', async ctx => ctx.body = await Birds.find({}))
I get an error that Birds is not defined. Plz tell me how to solve the
cat app.js problem
const Koa = require('koa');
const Router = require('koa-router');
const bodyParser = require('koa-bodyparser');
const config = require('config');
const handleErrors = require('./middlewares/handleErrors');
const db = require('./db');
 
const app = new Koa();
const router = new Router();
 
app.use(handleErrors);
app.use(bodyParser());

router.get('/articles', async ctx => ctx.body = await Articles.find({}))
 
router.post('/articles', async (ctx, next) => {
  const data = ctx.request.body;
  ctx.body = await db.Article.insertOne(data);
});

router.get('/articles/:id', async (ctx, next) => {
  const id = ctx.params.id;
  ctx.body = await db.Article.findOneById(id);
});

app.use(router.routes());
 
db
.connect()
.then(() => {
  app.listen(config.port, () => {
    console.info(`Listening to http://localhost:${config.port}`);
  });
})
.catch((err) => {
  console.error('ERR:', err);
});

catmodel.js
const ObjectId = require('mongodb').ObjectID;
 
class Model {
  constructor(db, collectionName) {
    this.name = collectionName;
    this.db = db;
  }

  async insertOne(data) {
    const operation = await this.db.collection(this.name).insertOne(data);
    if (operation.result.ok !== 1 || operation.ops.length !== 1) {
      throw new Error('Db insertOne error');
    }
    return operation.ops[0];
  }

  async findOneById(id) {
    let query = {
      _id: ObjectId(id)
    }
    const result = await this.db.collection(this.name).findOne(query);
    if (!result) {
      throw new Error('Db findOneById error');
    }
    return result;
  }
}
 
module.exports = Model;

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
AlexZeDim, 2017-04-16
@AlexZeDim

It depends on in what form, where and how they need to be obtained. An example with mongoose that 100% displays all the documents that are already in the collection:
First: npm i mongoose and in package.json add:

"dependencies": {
    "mongodb": "^2.2.25", //сама MongoDB, она должна быть обязательно
    "mongoose": "4.8.0", //это для mongoose - мангуст, наш случай
    "mongo": "~2.2.25" //это для mongo-native-driver, если работаем через него
}

var mongoose = require('mongoose'); //берем мангуст
mongoose.connect('mongodb://localhost/в_какую_базу_коннектимся'); //указываем куда


var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {}); //коннектимся к базе

var Schema = new mongoose.Schema({ //задаем схему
    поле: Значение,
    field: String
});

var server = mongoose.model('имя коллекции',Schema); //схему-в-модель

server.find({}, null, {sort: 'критерий сортировки'},function (err, res) {
    console.log (res); //вот здесь будут все документы
});

The same, only for mongo-native-driver, right on the main page with documentation with the title Find all Documents
If there is a need to simply see what documents are currently inside the collection, then this code through mongo-shell can help
var collections = db.getCollectionNames();
for(var i = 0; i< collections.length; i++) {    
   print('Collection: ' + collections[i]); // print the name of each collection
   db.getCollection(collections[i]).find().forEach(printjson); //and then print     the json of each of its elements
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question