Mongoose Document.prototype.toString()函数
Mongoose的Document.prototype.toString() API是用于Document模型的。它允许以字符串形式获取结果。使用此方法,我们可以将输出转换为字符串类型。让我们通过一个示例来了解toString()方法。
语法:
document.toString();
参数:
该方法不接受任何参数。
返回值:
该方法以字符串格式返回值。
设置Node.js应用:
步骤1:
使用以下命令创建一个Node.js应用:
npm init
步骤2: 创建NodeJS应用程序后,使用以下命令安装所需的模块:
npm install mongoose
项目结构: 项目的结构将如下所示:
数据库结构: 数据库结构将如下所示,以下文档存在于集合中。
示例1: 在这个示例中,我们展示了toString()方法的功能。我们从集合中获取一个文档,并使用toString()方法将其结果转换为字符串。
文件名:app.js
// Require mongoose module
const mongoose = require("mongoose");
// Set Up the Database connection
const URI = "mongodb://localhost:27017/geeksforgeeks";
const connectionObject = mongoose.createConnection(URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
const Customer = connectionObject.model(
"Customer",
new mongoose.Schema({
name: String,
address: String,
orderNumber: Number,
})
);
Customer.find({ name: "Harshit" }).then(res => {
console.log(res.toString());
}).catch(err => {
console.log(err);
})
运行程序的步骤: 要运行此应用程序,请从项目的根目录执行以下命令:
node app.js
输出:
{
_id: new ObjectId("63c1c0294a390b560860be13"),
name: 'Harshit',
address: 'Pune',
orderNumber: 45,
__v: 0
}
示例2: 在这个示例中,我们演示了toString()方法的功能。最后,我们验证了使用toString()方法将结果转换为字符串的类型。
文件名:app.js
// Require mongoose module
const mongoose = require("mongoose");
// Set Up the Database connection
const URI = "mongodb://localhost:27017/geeksforgeeks";
const connectionObject = mongoose.createConnection(URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
const Customer = connectionObject.model(
"Customer",
new mongoose.Schema({
name: String,
address: String,
orderNumber: Number,
})
);
Customer.find({ _id: "639ede899fdf57759087a653" }).then(res => {
const stringData = res.toString();
console.log(typeof stringData)
}).catch(err => {
console.log(err);
})
运行程序的步骤: 从项目的根目录中执行以下命令来运行应用程序:
node app.js
输出:
string
参考: https://mongoosejs.com/docs/api/document.html#document_Document-toString