Mongoose Document prototype.get()函数
The API prototype.get() 方法用于获取mongoose文档对象中任意字段的值。它可以用于Model对象获取集合中属性的值。
语法:
doc.get()
参数: 原型的 get() 方法接受三个参数。
- path: 这是您想要获取值的字段名称。
- type: 用于提取值的动态转换。
- options: 一个具有各种属性的对象。
返回值: prototype.get() 函数返回数据库中字段的值。
设置 Node.js 应用程序:
步骤1: 使用以下命令创建一个 Node.js 应用程序:
npm init
步骤2: 创建NodeJS应用程序后,使用以下命令安装所需模块:
npm install mongoose
项目结构: 项目的结构将如下所示:
数据库结构: 数据库结构将会如下所示,以下文件存在于集合中。
示例1: 在此示例中,我们使用mongoose建立了数据库连接,并定义了userSchema上的模型,其中包含两个列或字段“name”和“age”。最后,我们在User模型对象上使用 get() 方法。首先,我们使用对象ID获取文档对象,然后使用 get() 获取“name”字段的值。
- app.js: 将以下代码写入app.js文件中:
// Require mongoose module
const mongoose = require("mongoose");
// Set Up the Database connection
mongoose.connect("mongodb://localhost:27017/geeksforgeeks", {
useNewUrlParser: true,
useUnifiedTopology: true,
});
const userSchema = new mongoose.Schema({
name: String,
age: Number,
});
// Defining userSchema model
const User = mongoose.model("User", userSchema);
const getValue = async () => {
const doc = await User.findById(
"63203694182cd3c22ea480ff")
const value = doc.get("name")
console.log(value)
};
getValue();
运行程序的步骤: 要运行应用程序,请从项目的根目录执行以下命令:
node app.js
输出:
User1
示例2: 在这个示例中,我们在User模型对象上使用get()方法。我们使用promise来获取文档对象,并在文档对象上访问 get() 来获取“age”字段的值。在下面的示例中,我们将结果转换为字符串格式。你可以看到第一个console.log()打印了我们使用 get() 动态类型的值的类型,第二个console.log()打印了“age”字段的值。
- app.js: 将下面的代码写入app.js文件中:
// Require mongoose module
const mongoose = require("mongoose");
// Set Up the Database connection
mongoose.connect("mongodb://localhost:27017/geeksforgeeks", {
useNewUrlParser: true,
useUnifiedTopology: true,
});
const userSchema = new mongoose.Schema({
name: String,
age: Number,
});
// Defining userSchema model
const User = mongoose.model("User", userSchema);
User.findById("63203694182cd3c22ea480ff").then(doc => {
const value = doc.get("age", String);
console.log(typeof value);
console.log(value);
});
运行程序的步骤: 在项目的根目录下执行以下命令来运行应用程序:
node app.js
输出:
string
10
参考: https://mongoosejs.com/docs/api/document.html#document_Document-get