mongoose 入門筆記,mongoose入門

來源:互聯網
上載者:User

mongoose 入門筆記,mongoose入門
無論你什麼資料庫做db服務,connect都是必不可少的步鄹。方式一:

@param {String} uri@param {Object} options@param {Function} callbackconnect(uri,[options],[callbakc])返回mongoose對象mongoose.connect('mongodb://localhost/test',{mongos : true},function(err,result){    if(err){        console.log('Error connecting to MongoDB Database. ' + err);    }else{        loggers.info('Error connecting to MongoDB Database. ');        console.log('Connected to Database');    }   })

我們來看下connect 的實現

Mongoose.prototype.connect = function() {       var conn = this.connection;      if (rgxReplSet.test(arguments[0]) || checkReplicaSetInUri(arguments[0])) {            conn.openSet.apply(conn, arguments);      } else {            conn.open.apply(conn, arguments);      }      return this;};
方式二:
@param {String} uri@param {Object} optionscreateConnection([uri],[options])注意:這裡返回的是一個連線物件(也就是一個connect)這裡如果你產生了多個connect對象,那麼他們對應mongo裡的一個db,這個方法可以有助於我們同時操作多個db.例如:var opts = { server: { auto_reconnect: false },     user: 'username', pass: 'mypassword' };db = mongoose.createConnection('localhost', 'database', port, opts)

定義model

var Mongoose = require('mongoose');                                                                                        var Schema = Mongoose.Schema;var Product = new Schema({    image : {               type : String,          },      description : {                       type : String                  },      price : {                 type : Number,                require : true            },      probability : {                       type : Number,                      require : true                  },      status :{                type : Number,                require : true,                default : 1             }   },{    _id : true,        autoIndex : true});module.exports = Mongoose.model('Product',Product);

執行

router.get('/add',function(req,res){    var product = new Product({        image : 'images/product/id1.jpg',        descript : '這個產品挺好的',        price : 20.12,        probability : 100,        status : 1    })    product.save(function(err){        if(err){            console.log(err);        }else{            res.json({                msg:'ok'            })          }       })  })

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.