我有一个架构文章定义为:
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,
})
我需要查询编辑器创建的所有文章,即用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`
答案 0 :(得分:1)
MongoDB中没有连接的概念,因为它不是关系数据库。
populate方法实际上是Mongoose的一个功能,并在内部使用多个查询来替换引用的字段。
这必须使用多部分查询来完成,首先在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)
})
})
}