xgqfrms™, xgqfrms® : xgqfrms's offical website of cnblogs! xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!

MongoDB and Mongoose in Action All In One

MongoDB and Mongoose in Action All In One

Node.js API Server

Mongoose Model

Mongoose v7.6.0: Model

// DB name ✅
mongoose.connect('mongodb://127.0.0.1:27017/database_name');
const MyModel = mongoose.model('Test', new Schema({ name: String }));
// Works
await MyModel.findOne();

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

Mongoose API

.findOne vs .find

Model.findOne() no longer accepts a callback ⚠️

// Find one adventure whose `country` is 'Croatia', otherwise `null`
await Adventure.findOne({ country: 'Croatia' }).exec();

// Select only the adventures name and length
await Adventure.findOne({ country: 'Croatia' }, 'name length').exec();
// find all documents
await MyModel.find({});

// find all documents named john and at least 18
await MyModel.find({ name: 'john', age: { $gte: 18 } }).exec();

// executes, name LIKE john and only selecting the "name" and "friends" fields
await MyModel.find({ name: /john/i }, 'name friends').exec();

// passing options
await MyModel.find({ name: /john/i }, null, { skip: 10 }).exec();

https://mongoosejs.com/docs/api/model.html#Model.findOne()

https://mongoosejs.com/docs/api/model.html#Model.find()

.updateMany vs .updateOne

const res = await Person.updateOne({ name: 'Jean-Luc Picard' }, { ship: 'USS Enterprise' });

const res = await Person.updateMany({ name: /Stark$/ }, { isDeleted: true });

https://mongoosejs.com/docs/api/model.html#Model.updateOne()

https://mongoosejs.com/docs/api/model.html#Model.updateMany()

.deleteOne vs .deleteMany

await Character.deleteOne({ name: 'Eddard Stark' });
// returns {deletedCount: 1}

await Character.deleteMany({ name: /Stark/, age: { $gte: 18 } });
// returns {deletedCount: x} where x is the number of documents deleted.

https://mongoosejs.com/docs/api/model.html#Model.deleteOne()

https://mongoosejs.com/docs/api/model.html#Model.deleteMany()

auto convert Mongoose model to MongoDB collection

// ❌ MongooseError: Operation `wikis.find()` buffering timed out after 10000ms
// mongoose.connect(`mongodb://localhost:27017/`, {useNewUrlParser: true})
// ✅ so
mongoose.connect(`mongodb://127.0.0.1:27017/so`, {useNewUrlParser: true})
.then(() => {
  console.log('✅');
})
.catch((err) => {
  console.log('❌', err);
});

const ArticleSchema = {
  title: String,
  content: String
};

// model ❓ db collection
// wiki => wikis ✅ 根据 model 自动创建的 collection
// const Article = mongoose.model("wiki", ArticleSchema);
// art => arts ✅ 根据 model 自动创建的 collection
const Article = mongoose.model("art", ArticleSchema);

image

image

Mongoose connect

mongodb://username:password@host:port/database?options

// mongoose ✅
mongoose.connect('mongodb://username:password@host:port/database?options...');

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

Mongoose model

// `UserModel` is a "Model", a subclass of `mongoose.Model`.
const UserModel = mongoose.model('User', new Schema({ name: String }));

// You can use a Model to create new documents using `new`:
const userDoc = new UserModel({ name: 'Foo' });
await userDoc.save();

// You also use a model to create queries:
const userFromDb = await UserModel.findOne({ name: 'Foo' });

https://mongoosejs.com/docs/api/model.html#Model()

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

Mongoose will add s to collection name by default. ⚠️

https://stackoverflow.com/a/42456884/5934465

Use the VSCode to inspect the API’s TypeScript type definitions

mongoose.model(name, [schema?], [collection?], [options?])
  export function model<TSchema extends Schema = any>(
    name: string,
    schema?: TSchema,
    collection?: string,
    options?: CompileModelOptions
  ): Model<
  InferSchemaType<TSchema>,
  ObtainSchemaGeneric<TSchema, 'TQueryHelpers'>,
  ObtainSchemaGeneric<TSchema, 'TInstanceMethods'>,
  ObtainSchemaGeneric<TSchema, 'TVirtuals'>,
  HydratedDocument<
  InferSchemaType<TSchema>,
  ObtainSchemaGeneric<TSchema, 'TVirtuals'> & ObtainSchemaGeneric<TSchema, 'TInstanceMethods'>,
  ObtainSchemaGeneric<TSchema, 'TQueryHelpers'>
  >,
  TSchema
  > & ObtainSchemaGeneric<TSchema, 'TStaticMethods'>;

  export function model<T>(name: string, schema?: Schema<T, any, any> | Schema<T & Document, any, any>, collection?: string, options?: CompileModelOptions): Model<T>;

  export function model<T, U, TQueryHelpers = {}>(
    name: string,
    schema?: Schema<T, any, any, TQueryHelpers, any, any, any>,
    collection?: string,
    options?: CompileModelOptions
  ): U;

https://stackoverflow.com/a/77250774/5934465

demos

database CRUD

const express = require("express");
const mongoose = require("mongoose");
// const bodyParser = require("body-parser");
// const ejs = require("ejs");

const app = express();

// app.use(bodyParser.urlencoded({
//   extended: true
// }));
// app.set('view engine', 'ejs');

app.use(express.static("public"));

// ❌ MongoParseError: option gssapiservicename is not supported
// mongoose.connect("mongodb://localhost:27017/?compressors=disabled&gssapiServiceName=mongodb", {useNewUrlParser: true});
// ❌ MongooseError: Operation `wikis.find()` buffering timed out after 10000ms
// mongoose.connect(`mongodb://localhost:27017/`, {useNewUrlParser: true})
// ✅ so
mongoose.connect(`mongodb://127.0.0.1:27017/so`, {useNewUrlParser: true})
.then(() => {
  console.log('✅');
})
.catch((err) => {
  console.log('❌', err);
});


const ArticleSchema = {
  title: String,
  content: String
};

// model ❓ db collection
const Article = mongoose.model("wiki", ArticleSchema);

app.route("/articles")
.get(async (req, res) => {
  const articles = await Article.find();
  console.assert(`articles =`, articles)
  articles.forEach((article, i) => {
    console.log(`article`, i, article);
  });
  // mongoose.connection.close();
  res.json({
    articles,
  });
  // res.send(articles);
});

// http://localhost:3000/articles

app.route("/articles/:articleTitle")
.get(async (req, res) => {
  const title = req.params.articleTitle;
  console.log(`title =`, title);
  // const article = await Article.find({title});
  const article = await Article.findOne({title});
  console.log(`article`, article);
  res.json({
    article
  });
  // res.send(article);
});

// http://localhost:3000/articles/REST

// app.route("/articles/:articleTitle")
// .get((req, res) => {
//   const title = req.params.articleTitle;
//   console.log(`title =`, title);
//   Article.find({title})
//   .then((article) => {
//     console.log(`article`, article);
//     res.json({
//       article
//     });
//     // res.send(article);
//   })
//   .catch((err) => {
//     console.log(err);
//   });
// });


app.get(`/add`, async (req, res) => {
  const {
    title,
    content,
  } = req.query;
  // create document
  const article = new Article({
    title,
    content,
  });
  const result = await article.save();
  console.log(`✅ save `, result);
  // _id: new ObjectId("652199dc56efcc33e4e80f3d"),
  // _id: new ObjectId("652196bbc2ca11f4cbc45b09"),
  console.log(`_id `, result._id);
  res.send("Successfully added a new article.");
});

// http://localhost:3000/add?title=CRUD&content=增查改删/增删改查
// http://localhost:3000/add?title=CRUD&content=%E5%A2%9E%E6%9F%A5%E6%94%B9%E5%88%A0/%E5%A2%9E%E5%88%A0%E6%94%B9%E6%9F%A5

app.get(`/delete`, async (req, res) => {
  const id = req.query.id;
  // ✅ db.wikis.find().pretty()
  // await UserModel.findOne({ id });
  console.log(`id `, id);
  const result = await Article.deleteOne({_id: new ObjectID(id)});
  // const result = await Article.deleteOne({_id: new ObjectId(id)});
  // const result = await Article.deleteOne({_id: ObjectId(id)});
  console.log(`delete `, result);
  res.send("Successfully deleted the document.");
});

// http://localhost:3000/delete?id=652199dc56efcc33e4e80f3d
// http://localhost:3000/delete?id=652196bbc2ca11f4cbc45b09

const port = 3000;
app.listen(port, () => {
  console.log(`http server is running on: http://localhost:${port}/`);
});
// http://localhost:3000/

/*

db.wiki.insertOne({title: "REST", content: "REST is short for REpresentational State Transfer. It's an architectural style for designing APIs."})

db.wiki.find().pretty()

{
  "_id" : ObjectId("652167ce2dc49222ad06fac0"),
  "title" : "REST",
  "content" : "REST is short for REpresentational State Transfer. It's an architectural style for designing APIs."
}

❓model 自动创建的 collection 数据为空,需要手动添加数据

db.wikis.insertOne({title: "REST", content: "REST is short for REpresentational State Transfer. It's an architectural style for designing APIs."})


*/

image

image

image

wikis ❓自动创建的 ✅

$ mongo
> use so;

> show dbs;
admin   0.000GB
config  0.000GB
local   0.000GB
so      0.000GB
test    0.000GB
> show tables;
student
teacher
wiki
wikis
> db.wikis.find().pretty()
{
	"_id" : ObjectId("65217ae22dc49222ad06fac1"),
	"title" : "REST",
	"content" : "REST is short for REpresentational State Transfer. It's an architectural style for designing APIs."
}

image

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

MongoDB x Mongoose

https://www.mongodb.com/developer/languages/javascript/getting-started-with-mongodb-and-mongoose/

MongoDB Connection URI

protocol://credentials@hostanme/IP:port/?options

image

https://www.mongodb.com/docs/drivers/node/current/fundamentals/connection/connect/#std-label-node-connect-to-mongodb

Standard Connection String Format

// mongodb ✅
mongodb://[username:password@]host1[:port1][,...hostN[:portN]][/[defaultauthdb][?options]]

mongodb://myDatabaseUser:D1fficultP%40ssw0rd@mongodb0.example.com:27017/?authSource=admin

Connection Options

https://www.mongodb.com/docs/drivers/node/current/fundamentals/connection/connection-options/#std-label-node-connection-options

CRUD

增查改删 (创建、读取、更新和删除)

CRUD is the acronym for CREATE, READ, UPDATE and DELETE.

CRUD 是 CREATE、READ、UPDATE 和 DELETE 的缩写

image

https://en.wikipedia.org/wiki/Create,_read,_update_and_delete

https://zh.wikipedia.org/zh-cn/增刪查改

refs

https://stackoverflow.com/questions/77249580/trouble-finding-a-specific-item-from-mongodb-using-nodejs/77249734#77249734

ObjectId

const ObjectId = require('mongodb').ObjectId;

https://stackoverflow.com/questions/22143090/error-referenceerror-objectid-is-not-defined/68821720#68821720

https://www.mongodb.com/community/forums/t/how-use-objectid-search-from-webhook-in-mongodb/102081



©xgqfrms 2012-2021

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

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


posted @ 2023-10-08 00:08  xgqfrms  阅读(27)  评论(4编辑  收藏  举报