将Webpack与Mongoose一起使用 - mongoose.model不是一个函数

时间:2016-12-06 20:51:37

标签: javascript node.js express mongoose webpack

我使用Webpack在浏览器中使用require模块;但是,我收到以下错误:

Uncaught TypeError: mongoose.model is not a function
    at Object.<anonymous> (bundle.js:44338)
    at __webpack_require__ (bundle.js:20)
    at Object.<anonymous> (bundle.js:48)
    at Object.<anonymous> (bundle.js:68)
    at __webpack_require__ (bundle.js:20)
    at bundle.js:40
    at bundle.js:43

我知道mongoose在浏览器中有一些限制,根据http://mongoosejs.com/docs/browser.html我甚至包含了建议的脚本标记,但仍然收到错误

我还使用mongoose正确导出了我的模块:

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

var ProductSchema = new Schema({
    imageURL: String,
    productName: String,
    productType: String,
    price: String
}, {collection: 'products'});

module.exports = mongoose.model('products', ProductSchema);

我的webpack.config.js也正确配置

var webpack = require('webpack');
var path = require('path');
var fs = require('fs');
var request = require('request');
var CaseSensitivePathsPlugin = require('case-sensitive-paths-webpack-plugin');

module.exports = {
    entry: "./main.js",
    output: {
        path: __dirname,
        filename: "bundle.js"
    },
    module: {
    loaders: [
      { test: /\.json$/, loader: 'json-loader' }
        ]
    },
    resolve: {
        extensions: ['', '.webpack.js', '.web.js', '.js', '.json']
    },
    node: {
        console: 'empty',
        fs: 'empty',
        net: 'empty',
        tls: 'empty'
    }
}

为什么会这样?如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

mongoose.model仅限服务器端。在客户端/浏览器上没有模型,因为客户端/浏览器没有数据库连接。你可以使用mongoose.Document,以保持模式DRY / isomorph。

http://mongoosejs.com/docs/unstable/docs/browser.html