如何使用 Node.js 在 Mongodb 集合中添加范围?
Mongoose.module是 node.js 最强大的外部模块之一。 Mongoose是一个 MongoDB ODM 即(对象数据库建模),用于将代码及其表示从 MongoDB 转换到 Node.js 服务器。 Mongoose模块提供了几个函数来操作 MongoDB 数据库集合的文档(参考此链接)
Range: Mongoose模块允许我们在 Mongodb 数据库集合的特定键中添加范围。
安装模块:
npm install mongoose
项目结构:
在本地 IP 上运行服务器:数据是 MongoDB 服务器所在的目录。
mongod --dbpath=data --bind_ip 127.0.0.1
示例 1:插入超出限值。
文件名- index.js:
Javascript
// Importing mongoose module
const mongoose = require("mongoose");
// Database Address
const url = "mongodb://localhost:27017/GFG";
// Connecting to database
mongoose
.connect(url)
.then((ans) => {
console.log("Connected Successful");
})
.catch((err) => {
console.log("Error in the Connection");
});
// Calling Schema class
const Schema = mongoose.Schema;
// Creating Structure of the collection
const collection_structure = new Schema({
name: {
type: String,
required: true,
},
marks: {
type: Number,
min: 10,
max: 100,
},
});
// Creating collection
const collections = mongoose.model("GFG2", collection_structure);
// Inserting one document
collections
.create({
// Inserting value of only one key
name: "GFG",
marks: 1001,
})
.then((ans) => {
console.log(ans);
})
.catch((err) => {
console.log(err.message);
});
Javascript
// Importing mongoose module
const mongoose = require("mongoose");
// Database Address
const url = "mongodb://localhost:27017/GFG";
// Connecting to database
mongoose
.connect(url)
.then((ans) => {
console.log("Connected Successful");
})
.catch((err) => {
console.log("Error in the Connection");
});
// Calling Schema class
const Schema = mongoose.Schema;
// Creating Structure of the collection
const collection_structure = new Schema({
name: {
type: String,
required: true,
},
marks: {
type: Number,
min: 10,
max: 100,
},
});
// Creating collection
const collections = mongoose.model("GFG2", collection_structure);
// Inserting one document
collections
.create({
// Inserting value of only one key
name: "GFG",
marks: 100,
})
.then((ans) => {
console.log(ans);
})
.catch((err) => {
console.log(err.message);
});
使用以下命令运行index.js文件:
node index.js
输出:在控制台输出中。
示例 2:插入有效值
文件名- index.js
Javascript
// Importing mongoose module
const mongoose = require("mongoose");
// Database Address
const url = "mongodb://localhost:27017/GFG";
// Connecting to database
mongoose
.connect(url)
.then((ans) => {
console.log("Connected Successful");
})
.catch((err) => {
console.log("Error in the Connection");
});
// Calling Schema class
const Schema = mongoose.Schema;
// Creating Structure of the collection
const collection_structure = new Schema({
name: {
type: String,
required: true,
},
marks: {
type: Number,
min: 10,
max: 100,
},
});
// Creating collection
const collections = mongoose.model("GFG2", collection_structure);
// Inserting one document
collections
.create({
// Inserting value of only one key
name: "GFG",
marks: 100,
})
.then((ans) => {
console.log(ans);
})
.catch((err) => {
console.log(err.message);
});
使用以下命令运行index.js文件:
node index.js
输出:在控制台输出中。