mongoose 连接数据库的坑

连接

const mongoose = require('mongoose')
mongoose.set('debug', true)
mongoose.connect('mongodb://***:***@setsuna.wang:27017/hust', {
    useNewUrlParser: true
})
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function () {
    // we're connected!
});

在定义schema的时候,如果不加第二个参数,那么即使你在model中定义了表名为‘user’,mongoose会智能的在表名末尾添加一个's',那么你查询的表就会变成‘users’表,所以,为了安全,务必加上{collection:'table_name'},例如

var studentSchema = new mongoose.Schema({
    username: String,
    phone: String,
    score: Array
}, {
    collection: 'student'
})
const student = mongoose.model('student', studentSchema);

增删改查 参考链接CSDN

;(async ()=>{
  //查 
  var t = await studentModel.find({})
  //改 //注意! : 若使用 xxx.save() 则只有 schema 声明过的对象才能通过对应的 setter 传递值进入 xxx._doc.xxx.value
  await  studentModel.update({_id:"ae86"},{$set:{username:"newwww"}})
  //增
  await studentModel.create({ username:'test',phone:'110'})
  //删除
  await studentModel.remove({phone:'110'})
  //$lt"(小于),"$lte"(小于等于),"$gt"(大于),"$gte"(大于等于),"$ne"(不等于)
  await userMode.find({"age": {"$lt": 18}})

  //简单分页查询
  Model.find({}).sort({'_id':-1}).skip(page * 5).limit(5)
  //复杂分页查询 要求前端返回一个 ObjectId
  if (id) {
      return Model.find({{'_id': {"$lt": id}}).sort({'_id':-1}).skip(page * 5).limit(5)
  }else {
      return Model.find({}).sort({'_id':-1}).skip(page * 5).limit(5)
  }
  
  //关闭连接
  mongoose.connection.close()
})()

好看地输出 object

function log(t) {
    console.log(JSON.stringify(t, null, 2))
}

其中2代表2个空格

防止函数声明式调用失效
( function a( ){ })()改写为;( function a( ) { })() 比较好,加一个分号防止上一行结尾没有分号导致的编译歧义

你可能感兴趣的:(mongoose 连接数据库的坑)