首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在DB中填充多个路径?

如何在DB中填充多个路径?
EN

Stack Overflow用户
提问于 2020-10-20 06:04:36
回答 1查看 114关注 0票数 0

我希望从嵌套模式中获得不同的值。如何填充它们,以便每个字段都显示其嵌套数据,而不是对象ID?我正在使用MongoDB和节点/快车。

--这是我的postDB,定义了post模式:

代码语言:javascript
复制
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);

,这是我的commentDB,它来自postDB:

代码语言:javascript
复制
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;

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

代码语言:javascript
复制
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。

例如:

代码语言:javascript
复制
{
            "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"
        }

这里是userDB:

代码语言:javascript
复制
    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});

获取用户

代码语言:javascript
复制
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: --我为userDB添加了commentDB和postDB引用的代码。还添加了GET用户,以了解它在邮递员中是如何工作的。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-10-20 06:14:50

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

代码语言:javascript
复制
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})
    }
});
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64439338

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档