简体   繁体   English

在 mongoose 中查找 ID 数组

[英]Find with array of IDs in mongoose

I make an API with Express.js and mongoose.我用 Express.js 和 mongoose 制作了 API。 I need to find users whose id is contained in an array.我需要找到 id 包含在数组中的用户。

// the array of ids
const followedIds = follow.map((f) => f.followed);

console.log(followedIds);
// return [ '5ebaf673991fc602045ed47f', '5ebc6fb9af8add09edd842e9' ]

All IDs in this array exist.此数组中的所有 ID 都存在。

Then I do:然后我这样做:

User.where('_id').in(followedIds).exec()
    .then((followedUser) => {

        console.log('followedUser', followedUser);
        // return []
});

followedUser should have two users objects with the matching ids. followedUser应该有两个具有匹配 id 的用户对象。

How can I resolve this?我该如何解决这个问题?

Thanks谢谢

PS: There is my User model PS:还有我的用户model

const mongoose = require('mongoose');

const user = new mongoose.Schema({
    username: { type: String, required: true },
    email: { type: String, required: true },
    password: { type: String, required: true },
    avatar: { type: String, default: '/images/avatar_default.jpg' },
    banner: { type: String, default: '/images/banner_default.jpg' },
    created_at: { type: Date, required: true },
    deleted_at: { type: Date, required: false },
}, { versionKey: false });

module.exports = mongoose.model('user', user);

You can use an $in operator and provide an array of IDs as is to the mongo.您可以使用$in 运算符并向 mongo 提供一个 ID 数组。 Eg you can query the users that has specified IDs from the array:例如,您可以从数组中查询具有指定 ID 的用户:

const followedUsers = await User.find({ _id: { $in: followedIDs } });
console.log(followedUsers);

But, make sure that your followedIDs is an array of ObjectId .但是,请确保您的followedIDsObjectId的数组。 MongoDB stores _id as an ObjectId , not the string. MongoDB 将_id存储为ObjectId ,而不是字符串。

db.inventory.insertMany([
   { item: "journal", qty: 25, status: "A" },
   { item: "notebook", qty: 50, status: "A" },
   { item: "paper", qty: 100, status: "D" },
   { item: "planner", qty: 75, status: "D" },
   { item: "postcard", qty: 45, status: "A" }
]);

db.inventory.find({ _id: { $in: [ObjectId("your_id_here")] } });

To generate such an array from the array of strings, use map :要从字符串数组生成这样的数组,请使用map

const followedIDs = yourArrayWithIDAsString.map(ObjectId);

.in method like .in方法如

User.find().where('_id').in(followedIds)

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

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