Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
522 views
Welcome To Ask or Share your Answers For Others

1 Answer

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'
}])

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...