MongoDB $lookup Objectid get empty array?

2019-01-15 21:49发布

问题:

I'm new to mongodb and practice aggregate with $lookup in mongoose following document, And i met a question really confusing.

I have user Schema

const userSchema = new Schema({
  userName: {type: String, index:{unique: true}},
  password: String,
  avatar: String
})

comment Schema

const commentSchema = new Schema({
  post: {type: Schema.Types.ObjectId, ref:'postModel'},
  author:{type: Schema.Types.ObjectId, ref:'userModel'},
  content: String,
  createTime: Date
})

and models commentModel= mongoose.model('commentModel', commentSchema) userModel = mongoose.model('userModel', userSchema) Then i do

commentModel.aggregate.([{$lookup: {
  from: 'userModel',
  localField: 'author',
  foreignField: '_id',
  as: 'common'
}])

But i get empty common in the query. According to the data in db, I shouldn't get this result. After searching i still can not find what's the mistake.

Last but not least, I need to use aggregate method, so i have to use $lookup on reference document, dose it make sense?

回答1:

The from field in $lookup is the collection name, not a model variable name. So if you are initializing the model like this

db.model('User', userSchema)

then the lookup query should be

commentModel.aggregate([{$lookup: {
  from: 'users',
  localField: 'author',
  foreignField: '_id',
  as: 'common'
}])