2

I know maybe this question has been asked quite many times here, I've went through several solutions people came with to similar questions but none of them seemed to help in my case.

I have two collections called users and posts and models for them look like this:

users

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;

posts

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;

I'm trying to get the posts of a user using this code:

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 mode reports that the following query is executed during the request:

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

which works perfectly fine in mongodb shell (I'm using Mongoclient) but with Mongoose this query returns an empty array.

The query I run in mongodb shell:

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

The results I get:

{ "_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" }

I'm at the very beginning on learning Node.JS and MongoDB, so maybe I've missed something.

Thank you in advance!

2
  • 1
    That's because your actual data contains strings and not ObjectId values. See the difference between _id and user in the documents you provide? Your mongoose Schema is expecting ObjectId, and you probably should update the data so that the user property has ObjectId values. Simply search here for "update all items in collection" or something similar. Commented Jun 1, 2017 at 7:49
  • Yes, probably you are right. I'll try to change the value type from string to ObjectId and see what happens. Thank you! Commented Jun 1, 2017 at 7:56

1 Answer 1

1

As Neil Lunn suggested, I checked the user field type and it was indeed of type String instead of ObjectId so there was a mismatch of types between the data stored in collection and the field type from the query.

I used this code to convert the user field type from String to ObjectId in my collection:

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

Now everything works as expected.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.