Model.Find() - 如何返回 ObjectId 数组



我有一系列类别标题。我想让函数从这些标题返回一个ObjectId数组。我该怎么做?

Category Model: {_id, title}

    const findCategoryIdsFromCategoryTitles = (titles) => {
        return Category.find({ title: { $in: titles } })._id
    }
    let titles = ["A1", "A2", "A3"]
    let categoryIds = findCategoryIdsFromCategoryTitles(titles)

您可以使用 Mongoose .select(( 方法来选择特定字段。

const findCategoryIdsFromCategoryTitles = (titles) => {
    return Category.find({ title: { $in: titles } }).select('_id'); // Here you are selecting only _id field
}

第一个解决方案:选择

const findCategoryIdsFromCategoryTitles = (titles) => {
    return Category.find({ title: { $in: titles } }).select({ "_id": 1}); // or select("_id")
}
let titles = ["A1", "A2", "A3"]
let categoryIds = findCategoryIdsFromCategoryTitles(titles)

第二种聚合解决方案

const findCategoryIdsFromCategoryTitles = (titles) => {
    return Category.aggregate([{$match: {title: {$in: titles}}}, {$project: {_id: 1}}])
}
let titles = ["A1", "A2", "A3"]
let categoryIds = findCategoryIdsFromCategoryTitles(titles)

要有一个数组 ID:

const findCategoryIdsFromCategoryTitles = async (titles) => {
    return await Category.find({ title: { $in: titles } }).select({ "_id": 1}); // or select("_id")
}
let categoryIds = await findCategoryIdsFromCategoryTitles(titles)
const result  = categoryIds.map(({_id})=>_id) 

const result = [ { _id: '5d2e8ea173d1914ddee9443e' } , { _id: '5d2e8ea173d1914ddee94431' }].map(({_id})=>_id);
console.log(result);

最新更新