Mongoose,无法从数据库

时间:2017-06-25 14:52:33

标签: node.js mongoose

我在console.log中的打印项目或数据库中的res.json有问题。

我做错了什么

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);
            }
        })
});

数据库产品的名称是:db.product 感谢

  

错误:   C:\用户\ Turqus \桌面\节点\产品\ node_modules \猫鼬\ LIB \ index.js:382         抛出新的mongoose.Error.MissingSchemaError(name);         ^   MongooseError:Schema尚未注册模型" product,productSchema"。   使用mongoose.model(名称,架构)       在Mongoose.model(C:\ Users \ Turqus \ Desktop \ node \ products \ node_modules \ mongoose \ lib \ index.js:382:13)

1 个答案:

答案 0 :(得分:0)

您必须先进行数据库连接。

更改此

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

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

mongoose.model()接受两个参数,即模型所用集合的名称,第二个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);
        }
    })
});