Mongoose getting started with mongoose
No matter what database you use as the db service, connect is an essential step. Method 1:
@ Param {String} uri @ param {Object} options @ param {Function} callbackconnect (uri, [options], [callbakc]) returns the mongoose Object. connect ('mongodb: // localhost/test', {mongos: true}, function (err, result) {if (err) {console. log ('error ing to MongoDB Database. '+ err);} else {loggers.info ('error connecting to MongoDB Database. '); console. log ('connectedto database ');}})
Let's take a look at the implementation of 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;};
Method 2:
@ Param {String} uri @ param {Object} optionscreateConnection ([uri], [options]) Note: A connection Object (that is, a connect) is returned) if you generate multiple connect objects, they correspond to a database in mongo. This method can help us operate multiple databases at the same time. for example: var opts = {server: {auto_reconnect: false}, user: 'username', pass: 'mypassword'}; db = mongoose. createConnection ('localhost', 'database', port, opts)
Define 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);
Run
Router. get ('/add', function (req, res) {var product = new Product ({image: 'images/product/id1.jpg', descript: 'This product is quite good ', price: 20.12, probability: 100, status: 1}) product. save (function (err) {if (err) {console. log (err);} else {res. json ({msg: 'OK '})}})})