首页 文章

猫鼬深深地生长

提问于
浏览
0

我有两个架构,

一个用于用户,另一个用于发布

在用户模式中,我有一个latestPost的属性,它可以是post模式中条目的ObjectId

当我加载用户对象时,

我想将lastestPost作为一个对象,包括作者用户模式中的用户名,其中作者是一个与用户模式中的_id字段匹配的ObjectId .

mongoose教程似乎使用了语法

User.findOne({ _id: req.user.id})
.populate('latestPost')
.populate({ path: 'latestPost', populate: 'author'})

但它不起作用

它正在显示

{ _id: 58f54fa51febfa307d02d356,
  username: 'test',
  email: 'test@test',
  firstName: 'test',
  lastName: 'test',
  __v: 0,
  latestPost:
   { _id: 58f54fa51febfa307d02d357,
     user: 58f54fa51febfa307d02d356,
     author: 58f54fa51febfa307d02d356,
     date: 2017-04-17T23:28:37.960Z,
     post: 'Test',
     __v: 0 } }

但我想要它表明

latestPost:
   { 
     author:  {
      username  : something
     }
   }

怎么做这样的事情?架构或查询的设计有问题吗?

var UserSchema = new Schema({
    username  : String,
    firstName : String,
    lastName  : String,
    email     : String,
    password  : String,
    views     : Number,
    latestPost      : { type: Schema.Types.ObjectId, ref: 'Post' }
});

var PostSchema = new Schema({
    user      : { type: Schema.Types.ObjectId, ref: 'User' },
    author    : { type: Schema.Types.ObjectId, ref: 'User' },
    date      : Date,
    body      : String
});

var User        = mongoose.model('User', UserSchema);
var Post        = mongoose.model('Post', PostSchema);

User.findOne({ _id: req.user.id})
.populate('latestPost')
.populate({ path: 'latestPost', populate: 'author'})
.exec(function(err, user) {
  if (err) res.json(err)
  console.log(user)
})

2 回答

  • 4

    也许只是这个 .

    我不认为你需要 .populate('latestPost') ,因为你的下一个 .populate() 应该照顾填充 latestPost . 也许这会干扰下一个 .

    User.findOne({ _id: req.user.id }).populate({ 
        path: 'latestPost',
        model: 'Post',
        populate: {
            path: 'author',
            model: 'User'
        }
    }).exec(function (err, user) {
    
    });
    
  • 0

    您还需要在populate函数中提供模型名称:

    var UserSchema = new Schema({
        username  : String,
        firstName : String,
        lastName  : String,
        email     : String,
        password  : String,
        views     : Number,
        latestPost      : { type: Schema.Types.ObjectId, ref: 'Post' }
    });
    
    var PostSchema = new Schema({
        user      : { type: Schema.Types.ObjectId, ref: 'User' },
        author    : { type: Schema.Types.ObjectId, ref: 'User' },
        date      : Date,
        body      : String
    });
    
    var User        = mongoose.model('User', UserSchema);
    var Post        = mongoose.model('Post', PostSchema);
    
    User.findOne({ _id: req.user.id})
    .populate('latestPost')
    .populate({ 
        model: 'Post', 
        path: 'latestPost', 
        select: 'author -_id'
    })
    .exec(function(err, user) {
      if (err) res.json(err)
      console.log(user)
    })
    

相关问题