简体   繁体   中英

How to display lines from mongoDB with node.js?

I'm new with js. So, I want to display lines from a table of my mongoDB.

This is my code:

'use strict';
var mongoose = require('mongoose');
var timestamp = require('./plugins/timestamp');
var toString = require('./plugins/to-string');
var alphanumeric = require('./plugins/alphanumeric');

var async = require('async');
var moment = require('moment');
var S = require('string');
var _ = require('lodash');

var car = require('./car');


var schema = new mongoose.Schema({
  make: {type: String, trim: true, required: true},
  model: {type: String, trim: true, required: true},
  seats: Number,
  plateNumber: {type: String, unique: true, trim: true, alphanumeric: true},
});

var cars = mongoose.model('car');

var query = car.find(null);
query.limit(3);


query.exec(function (err, cars {
  if (err) { throw err; }

  var c;
  for (var i = 0, l = c.length; i < l; i++) {
    c = c[i];
    console.log('------------------------------');
    console.log('ID : ' + c._id);
    console.log('Make : ' + c.make);
    console.log('model : ' + c.model);
    console.log('seats : ' + c.seats);
    console.log('------------------------------');
  }
});

the problem, I think, is in 'cars' cause I don't know how to deal with the exec().

anyone can help me please?

Thanks,

Model can be executed by using callback function or exec method.

exec returns you the Promise too.

exec

 .exec(function (err, user) {
      //
  });

in your code you have syntax error as you have mismatched the exec method

var query = car.find({});
query.limit(3);


query.exec(function (err, cars) {
    if (err) { throw err; }

    for (var i=0;i< cars.length; i++) {
        console.log('______________________________');
        console.log('ID : ' + cars[i]._id);
        console.log('Make : ' + cars[i].make);
        console.log('model : ' + cars[i].model);
        console.log('seats : ' + cars[i].seats);
        console.log('------------------------------');
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM