gpt4 book ai didi

javascript - 在表示 ObjectID 的字符串数组中查找 mongoose ObjectID 时出现问题

转载 作者:行者123 更新时间:2023-12-03 04:06:57 25 4
gpt4 key购买 nike

我需要在这样的数组中找到 mongoose objectID 的索引:

[ { _id: 58676b0a27b3782b92066ab6, score: 0 },
{ _id: 58676aca27b3782b92066ab4, score: 3 },
{ _id: 58676aef27b3782b92066ab5, score: 0 }]

我用来比较的模型是具有以下数据的 Mongoose 模式:

{_id: 5868d41d27b3782b92066ac5,
updatedAt: 2017-01-01T21:38:30.070Z,
createdAt: 2017-01-01T10:04:13.413Z,
recurrence: 'once only',
end: 2017-01-02T00:00:00.000Z,
title: 'Go to bed without fuss / coming down',
_user: 58676aca27b3782b92066ab4,
__v: 0,
includeInCalc: true,
result: { money: 0, points: 4 },
active: false,
pocketmoney: 0,
goals: [],
pointsawarded: { poorly: 2, ok: 3, well: 4 },
blankUser: false }

我正在尝试使用以下命令在上面的数组中查找 model._user 的索引:

var isIndex = individualScores.map(function(is) {return is._id; }).indexOf(taskList[i]._user);

其中 individualScores 是原始数组,taskList[i] 是任务模型。然而,这总是返回-1。它永远不会在数组中找到正确的_id。

最佳答案

我猜您的问题与查询返回 _id 的方式有关

如果您获得 _id 作为 String,您的代码应该可以工作,请检查下面的代码片段

但是,如果您获得 ObjectsId,则必须先将它们转换为 String

var individualScores = [
{ _id: "58676b0a27b3782b92066ab6", score: 0 },
{ _id: "58676aca27b3782b92066ab4", score: 3 },
{ _id: "58676aef27b3782b92066ab5", score: 0 }
]

var task = {
_id: "5868d41d27b3782b92066ac5",
updatedAt: new Date("2017-01-01T21:38:30.070Z"),
createdAt: new Date("2017-01-01T10:04:13.413Z"),
recurrence: 'once only',
end: new Date("2017-01-02T00:00:00.000Z"),
title: 'Go to bed without fuss / coming down',
_user: "58676aca27b3782b92066ab4",
__v: 0,
includeInCalc: true,
result: { money: 0, points: 4 },
active: false,
pocketmoney: 0,
goals: [],
pointsawarded: { poorly: 2, ok: 3, well: 4 },
blankUser: false
}

var isIndex = individualScores.map(
function(is) {
return is._id;
})
.indexOf(task._user);

console.log(isIndex)

关于javascript - 在表示 ObjectID 的字符串数组中查找 mongoose ObjectID 时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44507937/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com