nodejs应用程序mongoose数据库where子句与连接

我有一个架构文章定义为:

var ArticleSchema = new Schema({ title: String, content: String, creator: { type: Schema.ObjectId, ref: 'User' } }) 

和用户架构:

 var UserSchema = new Schema({ type: String, //editor, admin, normal username: String, password: String, }) 

我需要查询由编辑器创build的所有文章,即以sql语言

 select Article.title as title, Article.content as content from Article inner join User on Article.creator = User._id where User.type = 'editor' 

这是我所尝试过的

 exports.listArticle = function(req, res, next) { var creatorType = req.query.creatorType var criteria = {} if (creatorType) criteria = {'creator.type': creatorType} Article.find(criteria).populate('creator').exec(function(err, articles) { if (err) return next(err) //ok to send the array of mongoose model, will be stringified, each toJSON is called return res.json(articles) }) } 

返回的articles是一个空数组[]

我也试过Article.populate('creator').find(criteria) ,也没有与错误工作:

 utils.populate: invalid path. Expected string. Got typeof `undefined` 

在MongoDB中没有连接的概念,因为它不是一个关系数据库。

填充方法实际上是Mongoose的一个function,并在内部使用多个查询来replace引用的字段。

这将必须使用多部分查询完成,首先在User集合上,然后在Article集合上完成。

 exports.listArticle = function(req, res, next) { var creatorType = req.query.creatorType var criteria = {} if (creatorType) criteria = {'type': creatorType} User.distinct('_id', criteria, function (err, userIds) { if (err) return next(err); Article.find({creator: {$in: userIds}}).populate('creator').exec(function(err, articles) { if (err) return next(err) //ok to send the array of mongoose model, will be stringified, each toJSON is called return res.json(articles) }) }) }