mongoose 导出模块多页使用

db.js

//db.js
const mongoose = require('mongoose')

mongoose.connect('mongodb://localhost/learn', {useNewUrlParser: true, useUnifiedTopology: true}, err => {
    if (err) console.log(err)
    else console.log('连接成功')
})

module.exports = mongoose

model.js

const mongoose = require('./db')

let UserSchema = mongoose.Schema({
    name: {
        type: String,
        required: true
    },
    address: {
        type: String,
        required: true
    },
    age: Number
})

module.exports = mongoose.model('User',UserSchema,'userMes')

User.js

const Model = require('./model')

let admin = new Model({
    name: '李二狗',
    address: '四川省内江市东兴区',
    age: 18
})

admin.save(err => {
    if (err) console.log(err)
    else console.log('添加数据成功')

    Model.find({},(err, docs) => {
        if (err) console.log(err)
        else console.log(docs)
    })
})

上一篇:模块的删除


下一篇:mongoose