Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
527 views
in Technique[技术] by (71.8m points)

node.js - MongoDB $lookup Objectid get empty array?

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

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

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...