首页 > 解决方案 > 如何在我的数据库中填充多个路径?

问题描述

我想要嵌套模式中的不同值。如何填充它们以便每个字段都向我显示其嵌套数据而不是对象 ID?我正在使用 MongoDB 和 node/express。

这是我的 postDB,其中定义了 post 架构:

const mongoose = require('mongoose');


var postSchema = new mongoose.Schema({
        title: {
            type:String,
            required:true
        },
        body: {
            type:String,
            required:true
        },
      comments:[{
          type: mongoose.Schema.Types.ObjectId,
          ref: "comment"
      }],
      category:{
        type:String,
        required:true
    },
      creator: {
          type: mongoose.Schema.Types.ObjectId,
          ref: "user"
      }
  },{timestamps : true}
 

)
  


module.exports = mongoose.model('postData', postSchema);

这是我从 postDB 引用的 commentDB:

const mongoose = require('mongoose');
// Using the Schema constructor, create a new CommentSchema object
// This is similar to a Sequelize model
var CommentSchema = new mongoose.Schema({
    // `body` is of type String
    creator: {
      type: mongoose.Schema.Types.ObjectId,
      ref: "user"
  },
    body: String
  },{timestamps : true});
 
  var Comment = mongoose.model("comment", CommentSchema);
  
  module.exports = Comment;

这就是我试图填充的方式:

router.get('/READ', (req,res)=>{
  posts.find({}, function (err, post) {
    if (err) {
      console.log(err);
  }else{
    
      res.json({post})
      }
        }
      )
      .populate([{path:'creator'}, {path:'comments'}])
      
    })

然而,我从中得到的结果并没有填充每个对象 ID。

例如:

{
            "comments": [
                {
                    "_id": "5f8d91d8f8550044f0f755c8",
                    "creator": "5f84e5b1d893ac42dcc9cb78",
                    "body": "This looks cool",
                    "createdAt": "2020-10-19T13:17:12.323Z",
                    "updatedAt": "2020-10-19T13:17:12.323Z",
                    "__v": 0
                },
                {
                    "_id": "5f8d92e82ecfbe34b8f6375b",
                    "creater": "5f84e5b1d893ac42dcc9cb78",
                    "body": "hello",
                    "createdAt": "2020-10-19T13:21:44.463Z",
                    "updatedAt": "2020-10-19T13:21:44.463Z",
                    "__v": 0
                },
                
            ],
            "_id": "5f887cef6fd7d34548a592ea",
            "title": "A DESCRIPTIVE PARAGRAPH EXAMPLE",
            "body": "\"The room in which I found myself was very large and lofty. The windows were ",
            "category": "Finance",
            "creator": {
                "joined": "2020-10-15T12:14:23.888Z",
                "posts": [
                    "5f887cef6fd7d34548a592ea",
                    "5f887e0d6fd7d34548a592ec",
                    "5f887e266fd7d34548a592ed",
                    "5f887e586fd7d34548a592ee",
                    "5f89bfccc2bebd40b07b044a",
                    "5f89c36e906bbb27b84af897",
                    "5f89c7614199d52b141ff249",
                    "5f89c7ea4199d52b141ff24a",
                    "5f8c5ab175ef762ed89eddba",
                    "5f8c5be2d7fac046f0021d9f"
                ],
                "_id": "5f88481d00ed460960da90f8",
                "username": "kenwaysharma",
                "email": "kenwaysharma@gmail.com",
                "password": "$2b$10$p3qjmdSKWIF9qAagZoqbjuG34cjOgXTe5XYER0aowwviIS65COVlu",
                "__v": 0
            },
            "__v": 0,
            "updatedAt": "2020-10-20T05:42:56.320Z"
        }

这是用户数据库:

    username: {
        type: String,
        required: [true, "Username is required!"],
        unique: true,
        lowercase: true,
    },
    email:{
        type: String,
        required: [true, "Email is required!"],
        unique: true,
        lowercase: true,
        validate: [isEmail, "Please enter a valid email!"]
    },
    password:{
        type: String,
        required: [true, "Password is required!"],
        minlength: [6, "Enter atleast 6 characters!"],
    },
    comments:[{
        type: mongoose.Schema.Types.ObjectId,
        ref: "comment"
    }],

    posts:[{
        type: mongoose.Schema.Types.ObjectId,
          ref: "postData"
    }],
  },{timestamps : true});
  

获取用户

router.get('/USERS', (req,res)=>{
  User.find({}, function (err, user) {
      if (err) {
          console.log(err);
      }else{
          res.send(user)
          }
        }
      ).populate('comments') .populate('posts')

    })

如何在评论中获取创建者数据,而不仅仅是其对象 ID?

更新: 我还尝试在 .populate('comments', 'creator') 之类的评论中选择创建者,但它仍然在字符串中为我提供了创建者对象 ID。

更新 2: 我添加了 commentDB 和 postDB 引用的 userDB 的代码。还添加了 GET 用户只是为了看看它在邮递员中是如何工作的。

标签: node.jsmongodbexpressmongoose

解决方案


尝试链接多个填充方法并使用 exec 方法传递您的回调。

posts.find({})
.populate({
   path: 'comments',
   populate: {
       path: 'creator',
       model: 'user'
   }
})
.populate('creator')
.exec(function (err, post) {
    if (err) {
      console.log(err);
    }else{
        res.json({post})
    }
});

推荐阅读