老师,代码为啥会有这个报错呢

正在回答

登陆购买课程后可参与讨论,去登陆

1回答

同学你好,请把package.json、model.js、db.js中的代码粘贴出来,老师测试一下。

祝学习愉快!

  • 微微Vivian哦耶 提问者 #1

    package.json

    {

    "name": "test4",

    "version": "0.1.0",

    "private": true,

    "scripts": {

    "start": "node bin/www",

    "dev": "./node_modules/.bin/nodemon bin/www",

    "prd": "pm2 start bin/www",

    "test": "echo \"Error: no test specified\" && exit 1"

    },

    "dependencies": {

    "debug": "^4.1.1",

    "koa": "^2.7.0",

    "koa-bodyparser": "^4.2.1",

    "koa-convert": "^1.2.0",

    "koa-json": "^2.0.2",

    "koa-logger": "^3.2.0",

    "koa-onerror": "^4.1.0",

    "koa-router": "^7.4.0",

    "koa-static": "^5.0.0",

    "koa-views": "^6.2.0",

    "mongoose": "^6.2.8",

    "pug": "^2.0.3"

    },

    "devDependencies": {

    "nodemon": "^1.19.1"

    }

    }


    model.js

    // 数据模型(规范数据格式)


    const mongoose = require('./db')


    // 定义schema(数据规范)

    const UserSchema = mongoose.Schema({

    username: {

    type: String,

    required: true,      // 必填

    unique: true         // 唯一,不重复

    },

    password: String,

    age: Number,

    city: String,

    gender: {

    type: Number,

    default: 0          // 设置默认值,0-保密,1-男,2-女

    }

    }, {

    timestamps: true        // 时间戳,自动添加文档的创建时间

    })


    // 定义Model

    const User = mongoose.model('user', UserSchema)


    module.exports = {

    User

    }




    db.js

    // 连接数据库(mongodb的服务端)

    // 获取mongoose插件

    const mongoose = require('mongoose');


    const url = 'mongodb://localhost:27017';

    const dbName = 'comment2'


    // 连接数据库

    mongoose.connect(`${url}/${dbName}`, {

    useNewUrlParser: true,

    useUnifiedTopology: true

    });


    // 获取当前的连接对象

    const conn = mongoose.connection;


    // 监听错误

    conn.on('error', err => {

    console.error('mongoose连接出错', err)

    })


    module.export = mongoose;


    2022-03-24 18:09:16
  • 如下位置代码写错了,导致mongoose没有导出:

    https://img1.sycdn.imooc.com//climg/623c443909bd36e504230086.jpg

    正确写法如下:

    https://img1.sycdn.imooc.com//climg/623c445a0928439305750090.jpg

    同学试试。

    2022-03-24 18:33:55
问题已解决,确定采纳
还有疑问,暂不采纳

恭喜解决一个难题,获得1积分~

来为老师/同学的回答评分吧

0 星
请稍等 ...
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号

在线咨询

领取优惠

免费试听

领取大纲

扫描二维码,添加
你的专属老师