📜  如何使用 Node.js 将虚拟对象填充到mongoose模型中?

📅  最后修改于: 2022-05-13 01:56:52.279000             🧑  作者: Mango

如何使用 Node.js 将虚拟对象填充到mongoose模型中?

在Mongoose中, virtual是不存储在数据库中的属性,它们只是在逻辑上存在,不能根据这个属性直接查询。要了解有关虚拟的更多信息,请参阅这篇文章Mongoose Virtuals。

填充虚拟:

在 MongoDB 中, Population是将一个集合的文档中的指定路径替换为另一个集合的实际文档的过程。

Mongoose在创建过程中还支持大量虚拟属性。每当我们希望我们的虚拟属性引用任何其他集合的模型时,我们都必须填充它,以便它可以包含其他集合的文档。

安装Mongoose:

第 1 步:您可以访问链接 Install mongoose来安装mongoose模块。您可以使用此命令安装此软件包。

npm install mongoose

第 2 步:现在您可以使用以下命令在文件中导入mongoose模块:

const mongoose = require('mongoose');

数据库:我们的数据库 GFG 中有两个集合用户帖子

  • users: users集合有两个用户User1User2。
  • 帖子:帖子集合为空

最初数据库中的用户和帖子集合

执行:

  1. 创建一个文件夹并添加文件main.js。
  2. 为了填充虚拟,我们必须指定三个必要的选项:
    • ref:它包含我们要从中填充文档的模型的名称。
    • localField:它是当前集合的任何字段。
    • foreignField:它是我们要从中填充文档的集合的任何字段。

Mongoose将从ref中给出的模型中填充这些文档,其foreignField值将与当前集合的localField值匹配。

示例:现在我们将了解如何使用 Node.js 将虚拟对象填充到mongoose模型中。

main.js
// Requiring module
const mongoose = require('mongoose');
  
// Connecting to database
mongoose.connect('mongodb://localhost:27017/GFG',
    {
        useNewUrlParser: true,
        useUnifiedTopology: true,
        useFindAndModify: false
    });
  
// User Schema
const userSchema = new mongoose.Schema({
    username: String,
    email: String
})
  
// Post Schema
const postSchema = new mongoose.Schema({
    title: String,
    postedBy: mongoose.Schema.Types.ObjectId
})
  
// Creating and populating virtual property 'user' in postSchema
// will populate the documents from user collection if 
// their '_id' matches with the 'postedBy' of the post
postSchema.virtual('user', {
    ref: 'User',
    localField: 'postedBy', // Of post collection
    foreignField: '_id',    // Of user collection
    justOne: true
})
  
// Creating user and post models 
const User = mongoose.model('User', userSchema);
const Post = mongoose.model('Post', postSchema);
  
// Function to create a post by the user
const createPost = async (next) => {
    const user = await User.findOne({ _id: '60acfa48e82a52560c32ec0a' });
  
    const newPost = new Post({
        title: 'Post 1',
        postedBy: user._id
    })
  
    const postSaved = await newPost.save();
    console.log("post created");
  
    // The findPost will be called after the post is created
    next();
}
  
// Function to find the post and show the virtual property
const findPost = async () => {
    const post = await Post.findOne().populate('user');
    console.log(post.user);
}
  
// Creating the post then showing the virtual property on console
createPost(findPost);


使用以下命令运行main.js

node main.js

输出:

执行 main.js 后的输出

说明:这里我们通过_id字段查找User 1 ,然后创建一个帖子,其postedBy字段值将是User 1 _id字段值(因此帖子由User 1创建)。每当创建帖子时,将为帖子创建一个虚拟属性“用户”,该属性将填充用户模型的文档,其_id字段值与帖子的postedBy值匹配。

数据库:使用填充的虚拟属性user创建帖子后,我们可以在数据库的帖子集合中看到帖子 1 。但是这里我们看不到数据库中的属性用户,因为它是一个虚拟属性,它不会存储在数据库中。

使用填充的虚拟创建帖子后的帖子集合