node mongodb 案例代码

时间:2021-10-16 12:25:05

1.db:

var mongoose=require("mongoose");
mongoose.connect('mongodb://localhost:8686/mytest',function(err){
if(err){
console.log('err connect')
return
}
console.log('suc connect')
});
var Schema = mongoose.Schema;
//骨架模版
var movieSchema = new Schema({
doctor : String,
title : String,
language : String,
country : String,
year : Number,
summary : String,
poster : String,
flash : String
})
//模型
var zhou = mongoose.model('zhou', movieSchema);
module.exports=zhou;

2.find:

var zhou =require('./db.js')
zhou.find({},function(err,data){
if(err){
console.log('err to find')
return
}
console.log(data)
})

3.update:

var db=require('./db.js')
db.update({title:'zhoucongmin'},{title:'dskfjsdk',country:'china',language:'chinese'},function(err){
if(err){
console.log('err to change')
return
}
console.log('suc')
})

4.insert:

var zhou =require('./db.js')

var zhou = new zhou({
title: '黑衣人三',
doctor: 'zhoucongmin',
year: Math.random()*100,
flash: 'http://player.youku.com/player.php/sid/XNjA1Njc0NTUy/v.swf',
country: '美国',
language: '英语',
summary: '好片'
})
zhou.save(function(err) {
if (err) {
console.log('保存失败')
return;
}
console.log('suc save');
});