我用 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);
但是,请确保您的
followedIDs
是 ObjectId
的数组. 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/