mongoseデータベースまとめ

1581 ワード

  • https://cnodejs.org/topic/504b4924e2b84515770103ddあるお兄さんのまとめの上
  • テンプレートコードを自分でテストします
    var mongoose = require('mongoose')
    var mongodb = 'mongodb://localhost/root/data/db'
    
    mongoose.Promise = global.Promise
    var db = mongoose.connect(mongodb);
    
    
    // model
    var BookSchema = new mongoose.Schema({
        name: String,
        author: String,
        newTime: Date
    })
    // model
    mongoose.model('Book', BookSchema)
    //-------------------------------------------------------------------
    
    
    // model
    var Book = mongoose.model("Book")
    
    // 
    var book = new Book({
        name: "MEAN Web Development",
        author: "liang",
        newTime: new Date()
    })
    
    book.save(function(err){
        console.log('save status:', err ? 'failed' : 'success')
    })
    
    Book.find({},function(err,data){
        if(err){
            console.log(err)
            return
        }
        console.log(data)
        console.log("find  success")
    })
    
    Book.findOne({author:"liang"},function(err, data){
        if(err){
            console.log(err)
            return
        }
        console.log(data)
    })
    // ID 
    Book.findOne({author:"liang"},function(err, data){
        if(err){
            console.log(err)
            return
        }
        if(data){
            data.remove()
        }
    
        console.log(data)
    })
    
    
    //  or   and 
    var cond = {
        $or:[
            {author: 'Jane'},
            {author: 'lin'}
        ]
    }
    
    Book.find(cond, function(err,data){
        if(err){
            console.log(err)
            return
        }
        console.log(data)
    })
    
    

    個人ブログ:http://www.liangtongzhuo.com