在表示ObjectID的字符串数组中查找mongoose ObjectID

时间:2017-06-12 20:11:21

标签: javascript arrays node.js mongodb mongoose-schema

我需要在数组中找到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。

2 个答案:

答案 0 :(得分:1)

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

如果_idString,您的代码应该有效,请查看下面的代码段

但是如果相反,你得到ObjectsId s,你必须先将它们转换为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)

答案 1 :(得分:0)

我认为您的流程应该运行良好,您只需要转换' objectID'到String进行比较。使用.toString()转换为_id_user

喜欢吼叫:

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