javascript - 在 Mongoose 中查找 ID 数组

标签 javascript api express mongoose

我用 Express.js 和 Mongoose 制作了一个 API。
我需要找到 id 包含在数组中的用户。

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

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

此数组中的所有 ID 都存在。

然后我做:
User.where('_id').in(followedIds).exec()
    .then((followedUser) => {

        console.log('followedUser', followedUser);
        // return []
});
followedUser应该有两个具有匹配 id 的用户对象。

我该如何解决这个问题?

谢谢

PS:有我的用户模型
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);

最佳答案

您可以使用 $in operator并按原样向 mongo 提供一组 ID。例如。您可以从数组中查询具有指定 ID 的用户:

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

但是,请确保您的 followedIDsObjectId 的数组. 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")] } });

要从字符串数组生成这样的数组,请使用 map :

const followedIDs = yourArrayWithIDAsString.map(ObjectId);

关于javascript - 在 Mongoose 中查找 ID 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62001726/

相关文章:

javascript - 路线不适用于模块化结构

javascript - 使用ajax发送数据表单文件

javascript - 将数据从 websocket 发送到 socket.io

javascript - 谷歌图表 : How to add a caption to the color axis

laravel - postman 返回 HTML 而不是 JSON?

api - OpenAI ChatGPT (gpt-3.5-turbo) API 错误 : "InvalidRequestError: Unrecognized request argument supplied: messages"

api - 如何在 Twitter 状态更新中嵌入 iframe

mysql - 不要等待node js中的mysql数据库结果

javascript - 如何本地化用户并显示我网站的优质版本

javascript - `cond ? true : false` 曾经是好的语法吗?