nodejs下mongoose的使用

本文详细介绍如何使用Node.js的Mongoose库连接MongoDB数据库,包括数据库连接、模型创建、实例化学生对象并同步到数据库的过程。同时,展示了通过静态方法进行数据查找和更新的操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

先创建一个db.js 用于连接数据库

/**
 * Created by Danny on 2015/9/28 16:44.
 */
//引包
var mongoose = require('mongoose');
//创建数据库连接
var db = mongoose.createConnection('mongodb://127.0.0.1:27017/haha');
//监听open事件
db.once('open', function(callback) {
    console.log("数据库成功连接");
});
//向外暴露这个db对象
module.exports = db;

*student.js 创建学生模型(类)
*

/**
 * Created by Danny on 2015/9/28 16:47.
 */
var mongoose = require('mongoose');
var db = require("./db.js");

//一、创建了一个schema结构。
var studentSchema = new mongoose.Schema({
    name: { type: String },
    age: { type: Number },
    sex: { type: String }
});
//三、创建静态(类)方法  由Student类(模型)来调用
studentSchema.statics.zhaoren = function(name, callback) {
    this.model('Student').find({ name: name }, callback);
    // this.model('Student')指当前的类,记住就行
};
     //创建修改的静态(类)方法
studentSchema.statics.xiugai = function(conditions, update, options, callback) {
    this.model("Student").update(conditions, update, options, callback);
}
//二、创建了一个模型,就是学生模型,就是学生类。集合
//类是基于schema创建的。
var studentModel = db.model('Student', studentSchema);
//四、向外暴露
module.exports = studentModel;

app.js中创建学生实例,并同步到数据库
法一:

//定义了一个模型,学生模型,“学生类” 集合
var Student = require("./models/Student.js");
//实例化了一个学生类
var xiaoming = new Student({"name":"小明","age":12,"sex":"男"});
//保存这个学生实例到数据库  持久化 
xiaoming.save(function(){
   console.log("存储成功");
});

法二(推荐):

//定义了一个模型,学生模型,“学生类” 集合
var Student = require("./models/Student.js");

//用类来创建一个对象(工厂)
Student.create({"name":"小红","age":13,"sex":"女"},function(error){
   console.log("保存成功");
})
// 使用静态方法 由模型(类)来调用
Student.zhaoren("小明",function(err,result){
    console.log(result);
});
// 使用静态方法 由模型(类)来调用
Student.xiugai({"name":"小明"},{$set : {"age":30}},{},function(){
    console.log("改年龄成功");
});

更多参考:
https://cnodejs.org/topic/51ff720b44e76d216afe34d9

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值