首页 > 代码库 > node 通过mongoose实现 mongodb的增删改

node 通过mongoose实现 mongodb的增删改

node 通过mongoose实现 mongodb的增删改

 

 

新建文件test.js
内容如下:
 
var mongoose = require(‘mongoose‘), Schema = mongoose.Schema;mongoose.connect(‘mongodb://localhost/test‘);var BlogSchema = new Schema({   id        : {type : Number, index : true}  ,title       : {type : String}});mongoose.model("Blog", BlogSchema);var Blog = mongoose.model("Blog"); //获得model实例var blog1 = new Blog();blog1.id = 4;blog1.title="ully";blog1.save(function(err) {  //存储  if (err) {    console.log(‘save failed‘);  }  console.log(‘save success‘);});Blog.find({id:4},function(err,docs){//查询id为4的记录     console.log(docs);     console.log(‘find success‘);});Blog.update({id:4,title:"upill"},function(err,docs){//更新     console.log(docs);     console.log(‘update success‘);});Blog.remove({id:4},function(err,docs){//删除id为4的记录     console.log(docs);     console.log(‘remove success‘);});
 

注意:在monogo中执行数据库查看时,要查询blogs(此处blogs是因为定了blog的model,本人认为这是mongoose自动生成的表结构)表,即

  use test;
 db.blogs.find();

node 通过mongoose实现 mongodb的增删改