Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose Find By Ref ID

so I have two schemas, User und Company

const UserSchema = new mongoose.Schema({
    _createdAt: Date,
    company: {type: mongoose.Schema.Types.ObjectId, ref: 'company'},
    email: String,
});


const CompanySchema = new mongoose.Schema({
    _createdAt: {
        type: Date,
        required: true
    },
    name: {
        type: String,
        required: true
    }
});

const userModel = mongoose.model("user", UserSchema, "user");
const companyModel = mongoose.model("company", CompanySchema, "company");

I would now like to query for a specific User by his Company _id, but for some reason this is not working, it returns an empty array even though I have a user with the exact company ObjectId in my Database.

userModel.find({company: "5cfa4352ffc1c8135d8276a4"})
         .exec((err, user) => {
             console.log(user);
         }

In my mongo shell the command

db.user.find({company: "5cfa4352ffc1c8135d8276a4"})

returns the users as expected so why does this not work in mongoose? Thanks in advance

like image 471
Jan Schmutz Avatar asked Oct 18 '25 16:10

Jan Schmutz


1 Answers

If you want to find by that id you probably need to do this:

const mongojs = require('mongojs');
const ObjectId = mongojs.ObjectId;

db.user.find({company: ObjectId("5cfa4352ffc1c8135d8276a4")})

Since you are using moongose, you can get the ObjectId like this:

const mongoose = require('mongoose');
const objectId = mongoose.Types.ObjectId('569ed8269353e9f4c51617aa')
like image 54
Nicolae Maties Avatar answered Oct 20 '25 05:10

Nicolae Maties



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!