var kitty = new Cat({ name: 'Zildjian', friends: ['tom', 'jerry']});
kitty.age = 3;
4.使用save才真的存入
kitty.save(function (err) {
if (err) // ...
console.log('meow');
});
ps: 如果存入資料的欄位不在schema內則不會存入
ps: 如省略某些欄位沒寫,則不會顯示,亦可正常存入
var mongoose = require('mongoose');
mongoose.connect('mongodb://forclass1:test123@ds013898.mlab.com:13898/forclass');
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
console.log("connect");
});
var Cat = mongoose.model('Cat', {
name: String,
friends: [String],
age: Number,
});
var kitty = new Cat({ name: 'Zildjian', friends: ['tom', 'jerry']});
kitty.age = 3;
//使用save方法後才會存入
kitty.save(function (err) {
if (err) // ...
console.log('meow');
});
使用Promise
var User = mongoose.model('ac', new mongoose.Schema({
name:{type: String, unique: true},
password:String
}));
var list = new User({name:"s", password:"123456"});
list.save()
.then(a => console.log(a))
.catch(err => console.log(err));
kittySchema.methods.speak = function () {
var greeting = this.name
? "Meow name is " + this.name
: "I don't have a name";
console.log(greeting);
}
完整版
var mongoose = require('mongoose');
mongoose.connect('mongodb://forclass1:test123@ds013898.mlab.com:13898/forclass');
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
console.log("connect");
});
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);
}
//////////method要定義在model實例化之前
var Kitten = mongoose.model('cats', kittySchema);
var fluffy = new Kitten({ name: 'fluffy' });
fluffy.speak(); // "Meow name is fluffy"