2
votes

I have problem with print items in console.log or res.json from database.

what am I doing wrong

var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/test');

var Schema = mongoose.Schema;
var productSchema = new Schema({
    title: String,
    price: Number
});

var product = mongoose.model('product, productSchema');
mongoose.connect(db);
var db = 'mongodb://localhost/product';

router.get('/books', function(req, res) {
    console.log('getting all products');

    product.find({})
        .exec(function(err, product) {
            if (err) {
                res.send('errror');
            } else {
                console.log(product);
                res.json(product);
            }
        })
});

name of database products is : db.product Thanks

Error: C:\Users\Turqus\Desktop\node\products\node_modules\mongoose\lib\index.js:382 throw new mongoose.Error.MissingSchemaError(name); ^ MongooseError: Schema hasn't been registered for model "product, productSchema". Use mongoose.model(name, schema) at Mongoose.model (C:\Users\Turqus\Desktop\node\products\node_modules\mongoose\lib\index.js:382:13)

1

1 Answers

0
votes

You have to make the Database Connection first.

change this

var product = mongoose.model('product, productSchema');

to

var product = mongoose.model('product', productSchema);

mongoose.model() accepts two parameter the name of the collection your model is for and the 2nd the Schema

var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/test');

var Schema = mongoose.Schema;
var productSchema = new Schema({
    title: String,
    price: Number
});

var product = mongoose.model('product', 'productSchema');

router.get('/books', function(req, res) {
console.log('getting all products');

product.find({})
    .exec(function(err, product) {
        if (err) {
            res.send('errror');
        } else {
            console.log(product);
            res.json(product);
        }
    })
});