MongoDB and mongoose All In One

发布时间 2023-09-23 20:07:30作者: xgqfrms

MongoDB and mongoose All In One

MongoDB

$ xcode-select --install

$ brew tap mongodb/brew
$ brew update
$ brew install mongodb-community@7.0

The mongod server
The mongos sharded cluster query router
The MongoDB Shell, mongosh

https://docs.mongodb.com/manual/tutorial/install-mongodb-on-os-x/

$ docker pull mongodb/mongodb-community-server
$ docker run --name mongo -d mongodb/mongodb-community-server:latest
# $ docker run --name mongo -d mongodb/mongodb-community-server:5.0-ubuntu2004

$ docker container ls
$ docker exec -it mongo mongosh

db.runCommand(
   {
      hello: 1
   }
)

https://www.mongodb.com/docs/manual/tutorial/install-mongodb-community-with-docker/

https://www.runoob.com/mongodb/mongodb-databases-documents-collections.html

mongoose

const mongoose = require('mongoose');

const uri = 'mongodb+srv://username:badpw@cluster0-OMITTED.mongodb.net/' +
  'test?retryWrites=true&w=majority';

mongoose.connect(uri, {
  serverSelectionTimeoutMS: 5000
}).catch(err => console.log(err.reason));

// 可以使用 mongoose.connection 访问默认的连接实例

So far we've seen how to connect to MongoDB using Mongoose's default connection.
Mongoose creates a default connection when you call mongoose.connect().
You can access the default connection using mongoose.connection.

const conn = mongoose.createConnection('mongodb://[username:password@]host1[:port1][,host2[:port2],...[,hostN[:portN]]][/[database][?options]]', options);

const UserModel = conn.model('User', userSchema);

demos

import mongoose from "mongoose";
import autoIncrement from "mongoose-auto-increment";


export function dbConnection() {
  try {
    mongoose.connect("mongodb://0.0.0.0:27017", {
      useNewUrlParser: true,
      useUnifiedTopology: true,
    });
    // init autoIncrement ✅
    autoIncrement.initialize(mongoose.connection);
    console.log("DB connected successfully ");
  } catch (error) {
    console.log("Not connected ");
  }
}

image

https://www.npmjs.com/package/mongoose-auto-increment

(? 反爬虫测试!打击盗版⚠️)如果你看到这个信息, 说明这是一篇剽窃的文章,请访问 https://www.cnblogs.com/xgqfrms/ 查看原创文章!

refs

https://mongoosejs.com/docs/connections.html

https://stackoverflow.com/questions/77162816/how-to-setup-mongodb-id-autoincrement-in-nodejs-using-mongoose-auto-increment/77162871?noredirect=1#comment136030504_77162871



©xgqfrms 2012-2021

www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!

原创文章,版权所有©️xgqfrms, 禁止转载 ?️,侵权必究⚠️!