我有一组类别标题。我想让函数从这些标题中返回ObjectId
的数组。我该怎么办?
Category Model: {_id, title}
const findCategoryIdsFromCategoryTitles = (titles) => {
return Category.find({ title: { $in: titles } })._id
}
let titles = ["A1", "A2", "A3"]
let categoryIds = findCategoryIdsFromCategoryTitles(titles)
答案 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)
的第二个解决方案
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);