Mongodb安装以及使用

本文详细介绍MongoDB的下载、安装过程及mongoose库的使用方法,包括数据模型构建、数据库配置、模型创建与数据操作等核心步骤。

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

下载安装mongodb

地址 https://www.mongodb.com/try/download/enterprise

安装mongoose 用来操作mongodb

地址 http://www.mongoosejs.net/docs/index.html

npm -S install mongoose

安装mongodb 用来可视化操作mongodb

地址 https://robomongo.org/

在这里插入图片描述

  1. 上图所示 schema 是数据模型
  2. db是mongodb数据配置
    数据库配置
var mongoose = require('mongoose');
// 链接mongo
const DB_URL = 'mongodb://127.0.0.1:27017/test';
 mongoose.connect(DB_URL,{useUnifiedTopology:true,useNewUrlParser: true},function (err) {
  if(err){
      console.log("数据库连接失败!",err);
  }else{
      console.log("数据库连接成功!");
    
  }
})
module.exports = mongoose;

构建模型

const mongoose = require("../db/config")
// var mongoose = require('mongoose');
var Schema = mongoose.Schema;
const schema = new Schema({   //db中有一个Schema的构造函数 设置需要的字段格式
  // key: value 的设置
  name: {
    type: String, //类型首字母大写
    required: true  //定义必须存在
  },

  price: {
    type: Number,
    default: 0  //默认为0
  },

  costPrice: {
    type: Number,
    default: 0
  }
});

module.exports = mongoose.model("Shop_info",schema)

引用

var express = require('express');
var router = express.Router();
const shopInfo = require("../schema/shop_info")
router.get('/', function(req, res, next) {
  // 查询数据
  shopInfo.findOne({ 'name': '酸梅汤' }, function (err, person) {
    if (err) return handleError(err);
    // Prints "Space Ghost is a talk show host".
    res.send({a:person});
  });

});
router.get('/add/shopinfo', function(req, res, next) {
  let query = req.query
  //生成对象保存数据
  const shopInfoModel = new shopInfo(query);
  shopInfoModel.save()
  res.send(query);
});
//添加字段
router.get('/update/shopinfo', function(req, res, next) {
  // let query = req.query
  shopInfo.findOneAndUpdate({_id:"606d2d62e7ec970e98c0135e"},{
    $set: {nums:10}
  },(e)=>{
    res.send(e);
  })
  
});
module.exports = router;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值