简体   繁体   中英

Mongoose: find statement not executing

This router get function is entered, the log statement is printed to the console, but the find statement doesn't seem to be executing. Any obvious reasons?

const express = require('express');
const router = express.Router();
const mongoose = require('mongoose');

const Product = require('../models/product');

module.exports = router;

const url = "mongodb://xxxx@ds027425.mlab.com:xxxx/xxxx";

mongoose.Promise = global.Promise;
mongoose.createConnection(url, function(err) {
    if(err) {
        console.log('Error!!!' + err);
    } else {
        console.log('Connected to Database!');
    }
});

router.get('/product/specialvalue', function(req, res) {
    console.log('Get specialvalue called xxxx');

    Product.find({'special_value': true})
    .sort({'price': 1}) 
    .exec(function(err, products) {
        if(err) {
            console.error('Error retrieving special value products!');
            res.json(err);  
        } else {
            console.log("products = " + JSON.stringify(products));
           res.json(products);        
        }
    });

});

This is the Mongoose Model:

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

const ProductSchema = new Schema({
  producttype: String,
  name: String,
  brand: String,
  model: String,
  price: Number,
  list_price: Number,
  description: String,
  rating: Number,

Continuation of the model: (The system is compelling me to add more detail)

  item_no: String,
  special_value: Boolean,
  warranty: String,
  feature: [String],
  image: [String],

Continuation of the model:

  specification: {
    lowes_exclusive : Boolean,
    color : String,
    high_efficiency : Boolean,
    automatic_load_balancing : Boolean,
    product_capacity : String,
    large_items_cycle : Boolean,

Continuation of the model:

        exclusive_cycle : String,
        maximum_spin_speed : String,
        water_levels : String,
        number_of_rinse_cycles : String
      }
    });

Continuation of the model:

var Product = mongoose.model('Product', ProductSchema, 'product');
module.exports=Product;

Your issue is with how you are connecting the the database. mongoose.createConnection() returns a connection object to the database, but it does not set it to be mongoose's default connection. The reason why the find query is not executing is because Mongoose queues all the DB calls and waits for there to be an open connection before it processes them, instead of throwing an error when there is no connection. Using mongoose.connect() will solve your problem. You can read about it here http://mongoosejs.com/docs/api.html#index_Mongoose-connect

There are some differences when you use .createConnection instead of .connect .

Here's the refactored code that works:

const express = require('express');
const router = express.Router();
const mongoose = require('mongoose');
const url = "mongodb://xxxx@ds027425.mlab.com:xxxx/xxxx";
const Schema = mongoose.Schema;

mongoose.Promise = global.Promise;


const db = mongoose.createConnection(url, function(err) {
    if(err) {
        console.log('Error!!!' + err);
    } else {
        console.log('Connected to Database!');
    }
});

const ProductSchema = new Schema({
    producttype: String,
    name: String,
    brand: String,
    model: String,
    ...
    }
});

const Product = db.model('Product', ProductSchema);

router.get('/product/specialvalue', function(req, res) {
    console.log('Get specialvalue called xxxx');
    Product.find({'special_value': true})
        .sort({'price': 1})
        .exec(function(err, products) {
            if(err) {
                console.error('Error retrieving special value products!');
                res.json(err);
            } else {
                console.log("products = " + JSON.stringify(products));
                res.json(products);
            }
        });

 });

Check out this post for a very good explanation on how to use .createConnection

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