【node】------mongoose的基本使用------【巷子】
生活随笔
收集整理的這篇文章主要介紹了
【node】------mongoose的基本使用------【巷子】
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1、安裝mongoose
npm install mongoose?
2、啟動數據庫
mongod --dbpath d:\data\db?
3、引入mongoose模塊并連接數據庫
const mongoose = require("mongoose");mongoose.connect("mongodb://127.0.0.1:27017/test1",function(err) {if(err){console.log('連接失敗');}else{console.log("連接成功")} });?
??4、創建表以及字段類型
const User = mongoose.model("user",{name:String,age:Number })?5、增
const user = new User({name:"張三",age:19 })user.save().then((result)=>{console.log("成功的回調") },()=>{console.log("失敗的回調") })?6、刪
1、刪除指定數據 User.remove({name:"zhao"}).then((result)=>{console.log(result) })result:是一個對象 返回值是受影響條數2、刪除所有數據 User.remove({}).then((result)=>{console.log(result) })
//刪除指定ID
3、User.findByIdAndRemove(id值).then((result)=>{
})
?7、改
User.update({name:"ya"},{$set:{name:"hua"}},{multi:true}).then((result)=>{console.log(result) })multi:true 表示修改多條數據User.findByIdAndUpdate(id值,{$set:{需要修改的內容}}.then((result)=>{})
?
8、查
001查詢符合條件的所有數據
User.find({name:ya}).then((result)=>{console.log(result) })result是查到的數據?002、查詢所有數據
User.find().then((result)=>{console.log(result) })?003、查詢單條數據
User.findOne({name:"zhao"}).then((result)=>{console.log(result);})?004、條件查詢:
$lt(小于) $lte(小于等于) $gt(大于) $gte(大于等于) $ne(不等于);User.find({"age":{"$lt":20}}).then((result)=>{console.log(result);})User.find({"age":{"$lte":20}}).then((result)=>{console.log(result);})User.find({"age":{"$gt":20}}).then((result)=>{console.log(result) })User.find({"age":{"$gte":20}}).then((result)=>{console.log(result) })User.find({"age":{"$ne":19}}).then((result)=>{console.log(result) })?005、$in(包含 等于)??$nin(不包含 不等于)
User.find({"age":{"$in":[18,19]}}).then((result)=>{console.log(result)})User.find({"age":{"$nin":[18,19]}}).then((result)=>{console.log(result) })?006、$or(或)
User.find({"$or":[{name:"zhao"},{age:20}]}).then((result)=>{console.log(result) })?007、$exists (判斷當前關鍵字是否存在)
User.find({name:{"$exists":true}}).then((result)=>{console.log(result); })?008、查詢指定列 如果不想要id值 只需要設置_id:0
User.find({},{name:1,age:1,_id:0}).then((result)=>{console.log(result); })?009、升序降序 sort()
User.find().sort({age:1}).then((result)=>{console.log(result) })?010、模糊查詢 //
User.find({name:/a/}).then((result)=>{console.log(result) })User.find({name:/^z/}).then((result)=>{console.log(result); })User.find({name:/z$/}).then((result)=>{console.log(result); })?011、skip(n):查詢n條以后的數據
User.find().skip(3).then((result)=>{console.log(result); })?012、顯示n-m之間的數據 skip:跳過n條 limit 顯示m-n條
User.find().skip(3).limit(2).then((result)=>{console.log(result) })?
轉載于:https://www.cnblogs.com/nanianqiming/p/9069760.html
總結
以上是生活随笔為你收集整理的【node】------mongoose的基本使用------【巷子】的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: SDOI2018:荣誉称号
- 下一篇: linux服务器last查看关机记录