使用asynchronous瀑布填充查询选项

林试图mongoosepopulate查询选项,但我不知道为什么查询选项不起作用。

我有用户架构:

 const mongoose = require('mongoose'); const Schema = mongoose.Schema; const UserSchema = new Schema( { username: { type: String, required: true }, email: { type: String }, name: { type: String }, address: { type: String } }, { timestamps: true } ); module.exports = mongoose.model('User', UserSchema); 

和Feed模式:

 const mongoose = require('mongoose'); const Schema = mongoose.Schema; const FeedSchema = new Schema( { user: { type: Schema.ObjectId, ref: 'User' }, notes: { type: String, required: true }, trx_date: { type: Date }, status: { type: Boolean, Default: true } }, { timestamps: true } ); FeedSchema.set('toObject', { getters: true }); module.exports = mongoose.model('Feed', FeedSchema); 

我想通过user IDfind所有的feed ,我使用async waterfall像下面的代码:

 async.waterfall([ function(callback) { User .findOne({ 'username': username }) .exec((err, result) => { if (result) { callback(null, result); } else { callback(err); } }); }, function(userid, callback) { // find user's feed Feed .find({}) // .populate('user', {_id: userid._id}) <== this one also doesn't work .populate({ path: 'user', match: { '_id': { $in: userid._id } } }) .exec(callback); } ], function(err, docs) { if (err) { return next(err); } console.log(docs); }); 

有了上面的代码,我得到了所有的提要,而且好像查询选项根本不起作用,我做错了吗?

任何帮助将不胜感激。

不知道为什么你希望匹配“之后”填充时, _id的值是什么已经存储在"user"属性“之前”甚至填充。

因此,它实际上只是一个简单的“查询”条件,而不是: .find()

 async.waterfall([ (callback) => User.findOne({ 'username': username }).exec(callback), (user, callback) => { if (!user) callback(new Error('not found')); // throw here if not found // find user's feed Feed .find({ user: user._id }) .populate('user') .exec(callback); } ], function(err, docs) { if (err) { return next(err); } console.log(docs); }); 

记住当然, .findOne()返回整个文档,所以你只需要在新的查询_id属性。 另外请注意,初始瀑布function中的“杂耍”是不必要的。 如果有错误,那么它将“快速失败”到结束callback,否则通过结果不是。 贬低“找不到”到下一个方法。

当然,这是没有必要的,因为“承诺”已经存在了一段时间,你真的应该使用它们:

 User.findOne({ "username": username }) .then( user => Feed.find({ "user": user._id }).populate('user') ) .then( feeds => /* do something */ ) .catch(err => /* do something with any error */) 

或者确实使用MongoDB支持的$lookup

 User.aggregate([ { "$match": { "username": username } }, { "$lookup": { "from": Feed.collection.name, "localField": "_id", "foreignField": "user", "as": "feeds" }} ]).then( user => /* User with feeds in array /* ) 

这在输出上有点不同,而且实际上可以通过一些操作来改变它,但是这应该给你一个总的想法。

重要的是让服务器执行连接而不是发出多个请求通常会更好,这至less会增加延迟。