欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

mongoose5的简单使用

程序员文章站 2022-07-14 08:54:51
...
const mongoose = require('mongoose')
const url = 'mongodb://127.0.0.1:27017';
const options = { useNewUrlParser: true, useUnifiedTopology: true, dbName: 'GameCityCF', user: 'user', pass: 'zH_user*3343' };
mongoose.connect(url,options);
mongoose.connection.on('error', function (error) {
  console.log('数据库连接失败:' + error);
});
mongoose.connection.on('open', function () {
  console.log("------数据库连接成功!------");
});
mongoose.connection.on('close', function () {
  console.log("------数据库关闭连接!------");
});
mongoose.connection.on('connected', () => console.log('mongo connect success'));

// 定义一个模式
const Schema = mongoose.Schema;

// 创建Schema(模式)对象
var stuSchema = new Schema({
  name: String,
  age: Number,
  gender: {
    type: String,
    default: 'male'
  },
  addr: String
})

//映射 创建模型
const studentModel = mongoose.model('student', stuSchema)

const user = new studentModel({
  name: "小明",
  age: "20",
  addr: "天津"
})

// user.name="小王"
console.log(user)
user.save(function (err) {
  if (err) {
    return console.log(err);
  }
  // 已保存
  console.log('数据写入成功')
  mongoose.connection.close()
});
相关标签: js mongoose