美文网首页
mongoose 数据库总结

mongoose 数据库总结

作者: 梁同桌 | 来源:发表于2016-09-30 21:02 被阅读47次

    我自己测试模板代码

    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

    相关文章

      网友评论

          本文标题:mongoose 数据库总结

          本文链接:https://www.haomeiwen.com/subject/bqkryttx.html