var mongoose = require('mongoose'); // 后面跟随的配置是安全配置,防止控制台输出警告 mongoose.connect('mongodb://39.106.100.189:10050/test1', { useUnifiedTopology: true, useNewUrlParser: true }); // 如果有用户名 密码 可以使用 // mongoose.connect('mongodb://name:pwd@39.106.100.189:10050/test1', { useUnifiedTopology: true, useNewUrlParser: true }); var db = mongoose.connection; db.on('error', function () { console.log('error'); }); db.once('open', function() { console.log('success'); var kittySchema = mongoose.Schema({ name: String });
kittySchema.methods.speak = function () { var greeting = this.name ? "Meow name is " + this.name : "I don't have a name"; console.log(greeting); } // 简历表 var Kitten = mongoose.model('Kitten', kittySchema);
var fluffy = new Kitten({ name: 'fluffy' }); fluffy.speak(); // "Meow name is fluffy" fluffy.save(function (err, fluffy) { if (err) return console.error(err); fluffy.speak(); }); }); // 还有一种方式 更加简洁 var User = mongoose.model('User', { // 建立表 name: String, age: Number }); var fluffy = new User({ name: 'ming', age: 15 });
// assign a function to the "statics" object of our animalSchema animalSchema.statics.findByName = function(name, cb) { returnthis.find({ name: newRegExp(name, 'i') }, cb); };