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

时间:2019-07-17 07:40:17

标签: javascript mongoose

我有一组类别标题。我想让函数从这些标题中返回ObjectId的数组。我该怎么办?

Category Model: {_id, title}


    const findCategoryIdsFromCategoryTitles = (titles) => {
        return Category.find({ title: { $in: titles } })._id
    }

    let titles = ["A1", "A2", "A3"]
    let categoryIds = findCategoryIdsFromCategoryTitles(titles)

2 个答案:

答案 0 :(得分:0)

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

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

答案 1 :(得分:0)

第一个解决方案:select

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

let titles = ["A1", "A2", "A3"]
let categoryIds = findCategoryIdsFromCategoryTitles(titles)

使用aggregate

的第二个解决方案
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);