mongoose数据库连接和操作

时间:2023-12-12 10:39:02

! mongodb注意点:数据表名称一定要用复数,比如users,在使用model引用时也必须复数

var mongoose = require('mongoose')
mongoose.connect('mongodb://localhost:27017/hometown',{useMongoClient: true});
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function (callback) {
console.log('db service connected.')
});
//set schema
var blogSchema = new mongoose.Schema({
article_id: {type:Number,default:0},
title: String,
detail: String,
img: String,
view: {type:Number,default:0}
});
//pub model
var blogModel = db.model('towntrip',blogSchema);
blogModel.find(function(err,articles){ //find({},fn)
res.render('index', {title:'Home Town',articles:articles})
})
//add data
//var data = new blogModel({title:'Guanyin Mountain',detail:'With history culture,Guanyin Mountain is known for so many years.',img:'upload/img/a2.jpg',view:0})
//data.save() //update data
//blogModel.update({_id:'5850c66834d5c51918f04d4c'},{$set:{view:1}},function(err){});