下載安裝(https://www.runoob.com/mongod...
配置環(huán)境變量
創(chuàng)建dbpath文件夾
啟動: mongod --dbpath=/data
// 查詢所有數(shù)據(jù)庫show dbs// 切換/創(chuàng)建數(shù)據(jù)庫,當(dāng)創(chuàng)建一個集合(table)的時候會自動創(chuàng)建當(dāng)前數(shù)據(jù)庫use test// 得到當(dāng)前db的所有聚集集合db.getCollectionNames()// 查詢db.fruits.find()// 插入一條數(shù)據(jù)db.fruits.save({name:'蘋果',price:5})// 條件查詢db.fruits.find({price:5})db.fruits.find({price: {$lte: 10}})
mongodb更多相關(guān)操作 點(diǎn)擊
const mongoose = require("mongoose");// 1.連接mongoose.connect("mongodb://localhost:27017/test", { useNewUrlParser: true });const conn = mongoose.connection;conn.on("error", () => console.error("連接數(shù)據(jù)庫失敗"));conn.once("open", async () => { // 2.定義一個Schema - Table const Schema = mongoose.Schema({ category: String, name: String }); // 3.編譯一個Model, 它對應(yīng)數(shù)據(jù)庫中復(fù)數(shù)、小寫的Collection const Model = mongoose.model("fruit", Schema); try { // 4.創(chuàng)建,create返回Promise let r = await Model.create({ category: "溫帶水果", name: "蘋果", price: 5 }); console.log("插入數(shù)據(jù):", r); // 5.查詢,find返回Query,它實(shí)現(xiàn)了then和catch,可以當(dāng)Promise使用 // 如果需要返回Promise,調(diào)用其exec() r = await Model.find({ name: "蘋果" }); console.log("查詢結(jié)果:", r); // 6.更新,updateOne返回Query r = await Model.updateOne({ name: "蘋果" }, { $set: { name: '芒果' } }); console.log("更新結(jié)果:", r); // 7.刪除,deleteOne返回Query r = await Model.deleteOne({ name: "蘋果" }); console.log("刪除結(jié)果:", r); } catch (error) { console.log(error); }});
const blogSchema = mongoose.Schema({ title: { type: String, required: [true, '標(biāo)題為必填項(xiàng)'] }, // 定義校驗(yàn)規(guī)則 author: String, body: String, comments: [{ body: String, date: Date }], // 定義對象數(shù)組 date: { type: Date, default: Date.now }, // 指定默認(rèn)值 hidden: Boolean, meta: { // 定義對象 votes: Number, favs: Number }});// 定義多個索引blogSchema.index({ title:1, author: 1, date: -1 });const BlogModel = mongoose.model("blog", blogSchema);const blog = new BlogModel({ title: "nodejs持久化", author: "jerry", body: "...."});const r = await blog.save();console.log("新增blog", r);
// 定義實(shí)例方法?blogSchema.methods.findByAuthor = function () {???return this.model('blog').find({ author: this.author }).exec();}?// 獲得模型實(shí)例?const BlogModel = mongoose.model("blog", blogSchema);?const blog = new BlogModel({...});?// 調(diào)用實(shí)例方法?r = await blog.findByAuthor();?console.log('findByAuthor', r);
blogSchema.statics.findByAuthor = function(author) {??return this.model("blog")??.find({ author })??.exec();};?r=await BlogModel.findByAuthor('jerry')?console.log("findByAuthor", r);
?blogSchema.virtual("commentsCount").get(function() {??return this.comments.length;});?let r = await blog.findOne({author:'jerry'});?console.log("blog留言數(shù):", r.commentsCount);