John
John

Reputation: 57

An empty array is being returned with Mongoose, Node.js

I am writing code with node.js. Quite new to this and the problem is that mongoose returns an empty array. There must be a mistake somewhere in this code, but I cannot find it. Any ideas?

Dresses schema

var dressesSchema = mongoose.Schema({
    title:{
    type: String,
    required: true
},
description:{
    type: String,
    required: true
}
});

var Dress = module.exports = mongoose.model('Dress', dressesSchema);

Get dresses from database

module.exports.getDresses = function(callback, limit){
    Dress.find(callback).limit(limit);
};

Dress = require('./models/dress');

app.get('/api/dresses', function(req, res){
    Dress.getDresses(function(err, dresses){
        if(err){
            throw err;
        }
        res.json(dresses);
    });
});

Upvotes: 0

Views: 125

Answers (2)

Jaber Alshami
Jaber Alshami

Reputation: 404

try this:

Dresses schema :

const mongoose = require("mongoose");

const Schema = mongoose.Schema;

const Dress= new Schema({
 title:{
    type: String,
    required: true
},
description:{
    type: String,
    required: true
},
price:{
    type: String
},
stock:{
    type: String
},
location:{
    country:{
        type: String
    },
    city:{
        type: String
    },
    street:{
        type: String
    },
    lon:{
        type: String
    },
    lat:{
        type: String
    }
}
});

module.exports = mongoose.model("dress", Dress);

Get dresses from database:

const {Dress} = require('./models/dress');

Dress.find().then(result => {

    console.log(result);

    });

Upvotes: 0

Ariel Livshits
Ariel Livshits

Reputation: 591

example how to use find via mongoose :

// named john and at least 18
MyModel.find({ name: 'john', age: { $gte: 18 }});

// executes immediately, passing results to callback
MyModel.find({ name: 'john', age: { $gte: 18 }}, function (err, docs) {});

// name LIKE john and only selecting the "name" and "friends" fields, executing immediately
MyModel.find({ name: /john/i }, 'name friends', function (err, docs) { })

// passing options
MyModel.find({ name: /john/i }, null, { skip: 10 })

// passing options and executing immediately
MyModel.find({ name: /john/i }, null, { skip: 10 }, function (err, docs) {});

// executing a query explicitly
var query = MyModel.find({ name: /john/i }, null, { skip: 10 })
query.exec(function (err, docs) {});

// using the promise returned from executing a query
var query = MyModel.find({ name: /john/i }, null, { skip: 10 });
var promise = query.exec();
promise.addBack(function (err, docs) {});

taken from link

Upvotes: 2

Related Questions