原生mongod

image.png
mongoose
- 百度mongoose文檔
-
查看文檔
mongoose.png
-
- 安裝需要的依賴
- 代碼段如下
//引入 mongoose ,然后連接我們本地的 demo 數(shù)據(jù)庫(kù)。
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/demo', {
useUnifiedTopology: true,
useNewUrlParser: true
});
//connect() 返回一個(gè)狀態(tài)待定(pending)的連接, 接著我們加上成功提醒和失敗警告。
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function () {
// we're connected!
console.log('數(shù)據(jù)庫(kù)鏈接成功');
});
//創(chuàng)建 schema 集合的一個(gè)映射,規(guī)定了集合中的字段及其類型
var Schema = mongoose.Schema;
/*
字段驗(yàn)證:
1.type 類型 字符串 數(shù)字 對(duì)象 函數(shù)。。
String
Number
Date
Buffer
Boolean
Mixed
ObjectId
Array
2.非空驗(yàn)證 isRequired
3.默認(rèn)值 default
*/
//定義一個(gè)映射
const artSchema = new Schema({
title: String,
//描述
desc: {
type: String,
isRequired: true
},
//富文本數(shù)據(jù)
connect: {
type: String,
isRequired: true
},
author: {
type: String,
isRequired: true
}
})
//定義model模型,集合的實(shí)例(包含增刪改查)
//第二個(gè)tank為表名,schema為映射
// var Tank = mongoose.model('Tank', schema);
// Mongoose 會(huì)自動(dòng)找到名稱是 model 名字 復(fù)數(shù) 形式的 collection
//創(chuàng)建一個(gè)集合 arts
const artModel = mongoose.model('qf_arts', artSchema);
//增刪改查操作
// .find() 查詢 參數(shù) 同原生
// .update({},{}) 更新 參數(shù)1:條件 參數(shù)2:修改的值
// .insertMany() 還有一個(gè)回調(diào)函數(shù)
// .remove() 參數(shù)對(duì)象 同原生
artModel.insertMany({
title: '烤肉自帶水壺',
desc: '出土文物',
connect: '<div>后視鏡</div>',
author: '范困'
}, (err, docs) => {
if (err) {
console.log('插入數(shù)據(jù)失敗');
return;
}
console.log(docs);
})
