【问题标题】:Using Webpack with Mongoose - mongoose.model is not a function将 Webpack 与 Mongoose 一起使用 - mongoose.model 不是函数
【发布时间】:2017-04-21 15:22:49
【问题描述】:

我正在使用 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

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

我还正确地使用猫鼬导出了我的模块:

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'
    }
}

为什么会这样?又该如何解决?

【问题讨论】:

  • 只是想我会提到这发生在我身上,因为我的 Angular 2 单元测试由于服务器的帐户服务和 Angular 的帐户服务的文件名的微小差异而意外导入了错误的服务。

标签: javascript node.js express mongoose webpack


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-21
    • 2021-12-05
    • 2017-12-09
    • 2020-10-05
    • 2016-01-27
    • 1970-01-01
    • 1970-01-01
    • 2019-04-15
    相关资源
    最近更新 更多