Skip to main content

mongoose 基本設定

注意

以下為 cluod9 的 node.js 環境下操作

先到 v2 資料夾,安裝好mongoose

npm install mongoose --save

檢查 package.json 有無安裝好 Mongoose 接下來

在終端機 c9 最原本處執行 MongoDB

./mongod

在 app.js 內最上加入 mongoose 因此會有

var express    = require('express'),
app = express(),
bodyParser = require('bodyparser'),
mongoose = require('mongoose')

然後在終端機執行

node app.js

來測試看看有沒有問題

沒問題後,在 app.js 內連結 mongoose

mongoose.connect("mongodb://localhost/yelp_camp");

因此會有下列設定

mongoose.connect("mongodb://localhost/yelp_camp");
app.use(bodyParser.urlencoded({extended: true}));
app.set("view engine", "ejs");

接著測試看看 app.js ,可以之後來設定 Schema

// Schema Setup
var campgroundSchema = new mongoose.Schema({
name: String,
image: String
});

var Campground = mongoose.model("Campground", campgroundSchema);

設定好 Schema 後,測試看看是否能增加資料來使用,增加

Campground.create({
name: "Salmon Creek"
image: "(url)"
}, function(err, campground){
if(err){
console.log(err);
} else {
console.log("Newly Created Campground: ");
console.log(campground);
}
});
  • 終端機啟用 node app.js 試試有沒有成功。
  • 也在終端機輸入 mongo 然後 show dbs 試試看有沒有 yelp_camp 資料出現
  • 也可 use yelp_camp 看看
  • 再用 show collections 看看資料
  • 再用 db.campgrounds.find() 看看剛剛輸入的資料
  • Ctrl + C 關閉 mongo 伺服器繼續編輯
  • 現在刪除剛剛測試的資料
    name: "Salmon Creek"
image: "(url)"
},

修改連結 /campground 的地方

app.get("/campgrounds", function(req, res){
// Get all campgrounds from DB
Campground.find({}, function(err, allCampgrounds){
if(err){
console.log(err);
} else {
res.render("campgrounds",{campgrounds:allCampgrounds});
}
});
})

comment 之前測試能否使用 mongoose 的測試資料

// Campground.create({
// name: "Salmon Creek"
// image: "(url)"
// }, function(err, campground){
// if(err){
// console.log(err);
// } else {
// console.log("Newly Created Campground: ");
// console.log(campground);
// }
// });
  • 然後使用終端機 node app.js 來看看是否成功!
  • 成功後來解決一項問題,在前端介面輸入圖片url的時候若不輸入圖片,會有 campgrounds is not definded的情況
  • 問題在 app.post 部分的程式碼 campground.push(newCampground) 這邊是之前測試時推上剛剛 comment 掉的地方,於是我們要刪除這行,並修改成增加一段 Campground 且存到 DB 的程式碼,若不是則要跳到 campgrounds 頁面
// Create a new campground and save to DB
Campground.create(newCampground, function(err, newlyCreated){
if(err){
console.log(err);
} else{
// redirect back to campgrounds page
res.redirect("/campgrounds");
}
})

完成