【Mongoose】Mongoose增删改查

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/MyFuture_MyDream/article/details/57082598

数据库连接:db.js
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/DB/CURD');
var db = mongoose.connection;
db.once('open', function (callback) {
    console.log("数据库成功打开");
});
module.exports = db;
Students类创建:Student.js
var mongoose = require('mongoose');
//schema
var studentSchema = new mongoose.Schema({
    "sid" : Number,
    "name" : String,
    "age" : Number,
    "sex" : String,
    "Kechengs" : [Number] //存放课程的kid
});
//model
var Student = mongoose.model("Student",studentSchema);
module.exports = Student;
测试CURD

// var studentOpts ={
// "sid" : 1300,
// "name" : '小明',
// "age" : 19,
// "sex" : '男',
// "Kechengs" : [12,13,14] //存放课程的kid
// };
// // 增
// Student.create(studentOpts,function(err,result){
// console.log("成功");
// });
// Student.remove({"age":100},function(){
// console.log("删除成功!");
// });
// Student.update({"age":24},{$set:{"sex":"囡囡"}},function(err,result){
// console.log("成功");
// });
// 查询——查询所有数据
// Student.find({},function(err,result){
// //result就是所有学生数组 
// console.log(result);
// }); 
// 查询——查询指定数据
// Student.findOne({"name":"沙和尚"},function(err,result){
// //result就是所有学生数组 
// console.log(result);
// });
// 查询——查询所有结果,并排序排序
// Student.find().sort({"age":-1}).exec(function(err,result){
// console.log(result);
// }); 
// 查询——查询所有结果,排序并返回指定数量结果
// Student.find().sort({"age":-1}).limit(2).exec(function(err,result){
// console.log(result);
// }); 
// 查询结果,分页操作
// Student.find().sort({"age":1}).skip(3).limit(4).exec(function(err,result){
// console.log(result);
// });


猜你喜欢

转载自blog.csdn.net/MyFuture_MyDream/article/details/57082598