原生mongod
image.png
mongoose
- 百度mongoose文档
-
查看文档
mongoose.png
-
- 安装需要的依赖
- 代码段如下
//引入 mongoose ,然后连接我们本地的 demo 数据库。
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/demo', {
useUnifiedTopology: true,
useNewUrlParser: true
});
//connect() 返回一个状态待定(pending)的连接, 接着我们加上成功提醒和失败警告。
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function () {
// we're connected!
console.log('数据库链接成功');
});
//创建 schema 集合的一个映射,规定了集合中的字段及其类型
var Schema = mongoose.Schema;
/*
字段验证:
1.type 类型 字符串 数字 对象 函数。。
String
Number
Date
Buffer
Boolean
Mixed
ObjectId
Array
2.非空验证 isRequired
3.默认值 default
*/
//定义一个映射
const artSchema = new Schema({
title: String,
//描述
desc: {
type: String,
isRequired: true
},
//富文本数据
connect: {
type: String,
isRequired: true
},
author: {
type: String,
isRequired: true
}
})
//定义model模型,集合的实例(包含增删改查)
//第二个tank为表名,schema为映射
// var Tank = mongoose.model('Tank', schema);
// Mongoose 会自动找到名称是 model 名字 复数 形式的 collection
//创建一个集合 arts
const artModel = mongoose.model('qf_arts', artSchema);
//增删改查操作
// .find() 查询 参数 同原生
// .update({},{}) 更新 参数1:条件 参数2:修改的值
// .insertMany() 还有一个回调函数
// .remove() 参数对象 同原生
artModel.insertMany({
title: '烤肉自带水壶',
desc: '出土文物',
connect: '<div>后视镜</div>',
author: '范困'
}, (err, docs) => {
if (err) {
console.log('插入数据失败');
return;
}
console.log(docs);
})