node 使用mongoose数据库

1、npm -s  mongoose 安装

2、在项目根目录下新建mongo文件夹后新建index.js文件,index文件代码如下

'use strict'

const fs = require('fs')
const path = require('path')
const basename = path.basename(__filename)

const mongoose = require("mongoose");

const connectUrl = "mongodb://账号:密码@ip:端口/数据库名称";//url连接

const config = { poolSize: 400, useNewUrlParser: true, useCreateIndex: true, useUnifiedTopology: true };//连接配置

mongoose.connect(connectUrl, config);
mongoose.connection.on("error", function (error) {
  console.log("********************************");
  console.log("* mongodb connection error!   *");
  console.log("********************************");
});

mongoose.connection.once("open", function () {
  console.log("********************************");
  console.log("* mongodb connection success! *");
  console.log("********************************");
});
/**
 * 连接断开
 */
mongoose.connection.on('disconnected', function () {
  console.log('mongodb connection disconnected');
});
fs.readdirSync(__dirname).filter(file => {
  return (file.indexOf('.') !== 0) && (file !== basename) && (file.slice(-3) === '.js')
}).forEach(file => {
  require(path.join(__dirname, file))(mongoose)
})//读取mongo文件夹下除index.js文件的其他文件(model文件)
module.exports = mongoose.models;//exports model

2、model定义,在mongo文件夹下新建user.js文件,代码如下:

module.exports = function (mongoose) {
  return mongoose.model("User", new mongoose.Schema({
    name: { type: String, default: "" },
    passwrod: { type: String, default: "" },
    createdAt: {
      type: Date, default: function () {
        return Date.now() + 8 * 60 * 60 * 1000;
      }, index: { expires: "10d", background: true } //数据过期时间,到期自动删除,mongo时区不是北京时间,可以加8小时,也可以不加,加的话前端转换时区是0不是北京时间
    }
  }, { collection: "user", toObject: { virtuals: true }, toJSON: { virtuals: true } }))
}

// 其他参考mongoose 中文文档

3、 在其他文件中使用方法:

const { User } = require(../mongo);


User.find() //其他查询参考mongoose中文文档

mongoose中文文档

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

少十步

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值