简体   繁体   English

Mongoose按参考ID查找

[英]Mongoose Find By Ref ID

so I have two schemas, User und Company 所以我有两个模式,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. 我现在想通过他的公司_id查询特定用户,但由于某种原因这不起作用,它返回一个空数组,即使我的用户在我的数据库中有确切的公司ObjectId。

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

In my mongo shell the command 在我的mongo shell命令中

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

returns the users as expected so why does this not work in mongoose? 按预期返回用户,为什么这不适用于mongoose? Thanks in advance 提前致谢

If you want to find by that id you probably need to do this: 如果你想通过那个id找到你可能需要这样做:

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: 由于您使用的是moongose,因此可以像这样获取ObjectId:

const mongoose = require('mongoose');
const objectId = mongoose.Types.ObjectId('569ed8269353e9f4c51617aa')

Try this 尝试这个

const ObjectId = require('mongodb').ObjectID;

then 然后

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

I hope it will work 我希望它能奏效

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM