JianShaw / note

记录个人学习
2 stars 0 forks source link

mongoose操作 #3

Open JianShaw opened 7 years ago

JianShaw commented 7 years ago

简单记录一些常用的mongoose操作。

mongoose

var db = mongoose.connect('mongodb://localhost/test');

db.connection.on("error", function(error) {
    console.log("数据库连接失败:" + error);
});

db.connection.on("open", function() {
    console.log("数据库连接成功");
});
//定义一个schema
var user_schema = new mongoose.Schema({
         name: {
            type: String,
            required: true
        }
});
//定一个一个model
const User = db.model("User",user_schema)

保存操作

     new User({
        name: 'hahahah'

    }).save((err, info) => {
        if (err) throw new Error(err)
        console.log(info)
    })

查找find

      User.find({}, function(err, docs) {
                    /*docs是返回的数组*/
    });

查找一个

    User.findOne({ _id: "58a570d0c2376905867cbd33" }, (err, User) => {
        console.log(`User: _${User}`)
    })

更新

    User.update({
        name: "shaojian"
    }, {
        name: "shaojian2",
        phone: "18918049525"
    }, function(error) {
        if (error) {

        }
        res.json({ code: '0' })
    });```

删除

   User.remove({
   _id: "58a570d0c2376905867cbd33"  
   }, function(err) {
        if (err) throw new Error(err);
        res.json({ msg: "删除成功" })
            // removed!
    });