链接数据库
const mongoose = require('mongoose');
// 链接数据库
mongoose.connect('mongodb://127.0.0.1:27017/demo',{useNewUrlParser:true,useUnifiedTopology: true});
// 监听连接
mongoose.connection.on('open',err=>{
if(!err){
console.log('数据库连接成功');
}else{
console.log(err);
}
})
schema约束
const mongoose = require('mongoose');
const studentSchema = new mongoose.Schema({
id:{
type:String, // 类型为字符串
required:true, // 为必须填入
unique:true // 限制学号是唯一的
},
hobby:[String] // 为数组,类型为字符串
})
// 第一个参数为 元素集合,第二个为 约束实例
const studentModel = mongoose.model('student',studentSchema);
本文介绍如何使用Mongoose连接MongoDB数据库并监听连接状态,同时展示了如何定义Schema约束来确保数据的一致性和完整性。
612

被折叠的 条评论
为什么被折叠?



