Node.js 连接 MongoDB-查询数据库

本文详细介绍了如何使用Mongoose进行MongoDB数据库操作,包括连接数据库、创建User模型,执行查询、更新和删除数据,以及关键操作实例。

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

 

 

可以直接改,不用$set

 

//使用mongose模块 cnpm install mongoose --save
//1引入模块
let mongoose = require("mongoose");
//2链接数据库
//then()方法前返回的是一个promise对象
mongoose.connect("mongodb://127.0.0.1:27017/student").then(() => {
    console.log("链接数据库成功");
}).catch(err => {
    console.log(err);
});
//3创建一个集合规则
let userSchema = new mongoose.Schema({
    username: String,
    age: Number,
    sex: String
});
//4 利用规则创建集合
let Users = mongoose.model("Users", userSchema);
//5查询数据 查询所有数据
// Users.find().then(result => {
//     console.log(result);
// })

// Users.find({
//     age: 20
// }).then(result => {
//     console.log(result);
// })

// Users.find({
//     age: {
//         $gt: 20
//     }
// }).then(result => {
//     console.log(result);
// })


// Users.find().sort({
//     age: 1
// }).then(result => {
//     console.log(result);
// })


// Users.find().sort({
//     age: 1
// }).limit(3).skip(1).then(result => {
//     console.log(result);
// });



//修改数据
// Users.updateOne({
//     username: "小明"
// }, {
//     $set: {
//         age: 38
//     }
// }).then(result => {
//     console.log(result);
// })

//更新多条数据
// Users.updateMany({}, {
//     username: "小小明"
// }).then(result => {
//     console.log(result);
// })

//删除数据
// Users.findOneAndDelete({
//     age: 38
// }).then(result => {
//     console.log(result);
// })

// 删除多条数据
// Users.deleteMany({}).then(result => {
//     console.log(result);
// })

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值