node.js - Mongoose 返回空,而 mongodb shell 中的相同查询工作正常

标签 node.js mongodb mongoose mongoose-schema

我知道这个问题可能已经在这里被问过很多次了,我已经研究了人们针对类似问题提出的几种解决方案,但它们似乎对我的情况没有帮助。

我有两个名为 usersposts 的集合,它们的模型如下所示:

用户

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;

帖子

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;

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

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);
        });
    });
});

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

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 所建议的,我检查了用户字段类型,它确实是 String 类型而不是 ObjectId,因此集合中存储的数据与查询中的字段类型之间存在类型不匹配。

我使用此代码将我集合中的用户字段类型从 String 转换为 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);
    }
);

现在一切正常。

关于node.js - Mongoose 返回空,而 mongodb shell 中的相同查询工作正常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44301482/

相关文章:

node.js - 使用排序和跳过填充的 Mongoose 查询太慢

node.js - 使用请求解析查询数组并使用 express 接收

javascript - 单独函数中的 HTTP 请求[node.js/expressjs]

Node.js Redis 过期与新鲜内容

javascript - 如何停止 mongoose/javascript 向数组添加空值?

node.js - Mongoose Stream,如何更新每个文档?

python mongodb $match 和 $group

java - 如何使用 Java 驱动程序检索现有 MongoDB 集合的 validator ?

javascript - Express JS如何将对象推送到子对象数组

javascript - MongoDB 电影票务系统的数据结构