mongoose常用代码

mongoose常用代码

连接

var mongoose = require('mongoose');
mongoose.connect('mongodb://user:[email protected]:37447/dbname');
//mongoose.connect('mongodb://localhost/test');


var db = mongoose.connection;
db.on('error',console.error.bind(console,'connection error:'));
db.once('open',function(){
    console.log('connected.');
    db.db.collectionNames(function(err, names){
        console.log(names);
    })
})

创建Schema的best practice

mongoose-schema-creation

查询

var Schema = mongoose.Schema;
var messageSchema = new Schema({
    message: String,
    timestamp: Date,
    author: String,
    room: String,
    to: String
}, {collection: 'chats'});
var Msg = mongoose.model('Msg', messageSchema);

var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function () {
    console.log('connected.');
    //db.db.collectionNames(function (err, names) {
    //    console.log(names);
    //})
    Msg.find({}).limit(2).sort('-timestamp').exec(function(err,docs){
        console.log(docs);
    })
})

新增

你可能感兴趣的:(mongoose常用代码)