0

I'm new to Javascript and Node and I'm having MongoDB trouble. So I have managed to successfully connect to my database using the connection string (using mongoose). This is where I'm stuck, what I want to do is retrieve the first record of the database. Seems like a simple task, but maybe I'm not just understanding some syntax or something.

I think the solution involves something to do with Schemas? I haven't been able to get them to work though.

Here is my JavaScript file. Note the username and password have been omitted.

const mongoose = require('mongoose');

//url to connect to database
const url = 'mongodb://<username>:<password>@ds157614.mlab.com:57614/flight_data';

//connect to mongodb
mongoose.connect(url, { useNewUrlParser: true });

mongoose.connection.once('open', function()
{
  console.log('Connected successfully');

}).on('error', function(error)
{
  console.log('Connection Error: ', error);
});

Here is an example of a record in the database:

{
    "_id": {
        "$oid": "5c3538d8ae9fb3103c5b2691"
    },
    "data": {
        "plane_id": 2202,
        "temperature": 100
    },
    "airport": "KBUF"
}

I've messed around with mongoose.connection and got some info to display, but not what I wanted. I want the output to just be the first record in the database.

  • ordering is not guaranteed in `mongodb` see https://stackoverflow.com/questions/33018048/how-does-mongodb-order-their-docs-in-one-collection?lq=1 You could add timestamp feild and sort it based on that – 1565986223 Apr 09 '19 at 03:14
  • Thanks for the link, I think I understand now. I think mine does keep track, the "$oid" part is always increasing, and I think I can sort it by that. – Jessie L Smith Apr 09 '19 at 04:26

1 Answers1

1

AFAIK there's no such thing as fetching first record from database, but you could fetch a record or documents(same as rows in SQL context) from a schema(same as tables in SQL context). To achieve this, you need to create a model first.

const mongoose     = require('mongoose');
const Schema       = mongoose.Schema;

const bookSchema   = new Schema({
    title: { type:String },
    description: { type:String }
});

module.exports = mongoose.model('Book', bookSchema);

And fetch using

Book.find({ title:'search' }, function(err, books) {
  // TODO: Do whatever you want
});
PrivateOmega
  • 2,509
  • 1
  • 17
  • 27