如何使用 NodeJS 在 MongoDB 中设置文档值类型?
Mongoose.module是 node.js 最强大的外部模块之一。 Mongoose 是一个 MongoDB ODM,即(对象数据库建模),用于将代码及其表示从 MongoDB 转换到 Node.js 服务器。 Mongoose 模块提供了几个函数来操作 MongoDB 数据库集合的文档(请参阅此链接)。
值类型: Mongoose 模块允许我们将值类型添加到 MongoDB 的集合中,即 String 和 Number 数据类型。这使得收集模式变得僵化。
安装模块:
npm install mongoose
项目结构:
在本地 IP 上运行服务器: Data 是 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,
},
});
// Creating collection
const collections = mongoose.model("GFG2", collection_structure);
// Inserting one document
collections
.create({
// Inserting value of only one key
name: "GFG",
marks: "10q0", // Inserting wrong value
})
.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,
},
});
// Creating collection
const collections = mongoose.model("GFG2", collection_structure);
// Inserting one document
collections
.create({
// Inserting value of only one key
name: "GFG",
marks: "1000",
})
.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,
},
});
// Creating collection
const collections = mongoose.model("GFG2", collection_structure);
// Inserting one document
collections
.create({
// Inserting value of only one key
name: "GFG",
marks: "1000",
})
.then((ans) => {
console.log(ans);
})
.catch((err) => {
console.log(err.message);
});
使用以下命令运行index.js 文件:
node index.js
控制台输出: