简体   繁体   中英

Mongoose find query is not executing

I am trying to fetch some data from a mongodb. I am able to fetch the details from the model MyModel (defined in Server.js). But I can't execute the find method in the model Skill (defined in Skill.js).

Server.js

  let express = require('express');
  let app = express();
  var config = require('./config/config');
  let bodyParser = require('body-parser');
  var mongoose = require('mongoose');
  var cors = require('cors')
  var path = require("path");
  let Skill = require('./app/models/Skill');
  const dbURI = config.dbURI;
  app.use(cors());
  app.use(bodyParser.json(true));
  mongoose.connect(dbURI, {useNewUrlParser: true});
  mongoose.connection.on('connected', function () {
         console.log("Connected");
  }); 
  var MyModel = mongoose.model('Test', new Schema({ name: String 
  }));
  Skill.findOne(function(error, result) { 
           console.log("1",error,result);
  });
  MyModel.findOne(function(error, result) { 
           console.log("2",error,result); 
  });
  app.listen(config.appPort,function () {
          console.log('App running on port :: "' + config.appPort.toString() + '"');

  });

app/models/Skill.js

 var mongoose = require('mongoose');

 var skillSchema = new mongoose.Schema({
       name: String,
       length: String,
 });

 var Skill = mongoose.model('Skill', skillSchema,'Skill');
 module.exports = Skill; 

Output

   App running on port :: "8080"
   Conneccted
   2 null { _id: 5c6678215c50a65e59fc6a89, name: 'test', __v: 0 }

I haven't found any issues while creating the schema. Could someone help me to resolve the issue?

I can't test my suggestion at the moment, but one thing I noticed in your code is that you queries, as in

Skill.findOne(function(error, result) { 
       console.log("1",error,result);
});
MyModel.findOne(function(error, result) { 
        console.log("2",error,result); 
});

are not executed in the "connected" callback; may be it's not the main problem, but I would try to change the code as follows:

mongoose.connection.on('connected', function () {
    console.log("Connected");
    Skill.findOne(function(error, result) { 
       console.log("1",error,result);
    });
    MyModel.findOne(function(error, result) { 
        console.log("2",error,result); 
    });
});

The key thing is that each call ( .on , .findOne ) starts a promise , which encapsulates an asynchronous behaviour. I you place ,findOne invocation just after .on invocation, you can't be sure Mongoose's connection is ready when you starts .findOne ...

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