Mongoose返回空而mongodbshell中的相同查询正常工作

我知道这个问题在这里已经有很多次的问题了,我也经历了几个类似的问题,但是没有一个似乎对我有帮助。

我有两个名为users集合,他们的posts和模型如下所示:

用户

 var mongoose = require('mongoose').set('debug', true); var Schema = mongoose.Schema; var usersSchema = new Schema({ name: {type: String, required: true} }); var User = mongoose.model('user', usersSchema, 'users'); module.exports = User; 

post

 var mongoose = require('mongoose').set('debug', true); var Schema = mongoose.Schema; var postsSchema = new Schema({ content: String, user: { type: Schema.ObjectId, ref: 'users', required: true } }); var Post = mongoose.model('post', postsSchema, 'posts'); module.exports = Post; 

我正在尝试使用此代码获取用户的post:

 var Post = require('../models/posts'); ... router.get('/posts/user/:userId', function (req, res, next) { Post.find({user: req.params.userId}, function (err, posts) { Post.populate(posts, {path: 'user'}, function(err, posts) { res.send(posts); }); }); }); 

Mongoosedebugging模式报告在请求期间执行以下查询:

 posts.find({ user: ObjectId("592e65765ba8a1f70c1eb0bd") }, { fields: {} }) 

在mongodb shell(我正在使用Mongoclient)中工作完美,但与Mongoose这个查询返回一个空的数组。

我在mongodb shell中运行的查询:

 db.posts.find({ user: "592e65765ba8a1f70c1eb0bd" }) 

我得到的结果是:

 { "_id" : ObjectId("592e66b48f60c03c1ee06445"), "content" : "Test post 3", "user" : "592e65765ba8a1f70c1eb0bd" } { "_id" : ObjectId("592e66b98f60c03c1ee06446"), "content" : "Test post 4", "user" : "592e65765ba8a1f70c1eb0bd" } { "_id" : ObjectId("592e66bb8f60c03c1ee06447"), "content" : "Test post 5", "user" : "592e65765ba8a1f70c1eb0bd" } 

我刚开始学习Node.JS和MongoDB,所以也许我错过了一些东西。

先谢谢你!

正如Neil Lunn所build议的那样,我检查了用户字段types,确实是Stringtypes而不是ObjectId,所以存储在集合中的数据与查询中的字段types之间存在不匹配。

我使用这段代码将string中的用户字段types转换为我的集合中的ObjectId:

 db.getCollection('posts').find().forEach(function (post) { db.getCollection('posts').remove({ _id : post._id}); tempUserId = new ObjectId(post.user); post.user = tempUserId; db.getCollection('posts').save(post); } ); 

现在一切按预期工作。