【问题标题】:Issue finding mongoose ObjectID in array of strings representing ObjectIDs在表示 ObjectID 的字符串数组中查找 mongoose ObjectID 的问题
【发布时间】:2017-06-13 13:26:14
【问题描述】:

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

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

我用来比较的模型是一个带有以下数据的猫鼬模式:

{_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。

【问题讨论】:

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


    【解决方案1】:

    我猜您的问题与您的查询如何返回 _id 有关

    如果你得到_idString,你的代码应该可以工作,检查下面的sn-p

    但是如果你得到ObjectsIds,你必须先将它们转换为字符串

    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)

    【讨论】:

    • 谢谢@Santiago 我会仔细看看,看看是否能解决问题。 (我之前尝试过,但 ObjectIds 出现转换错误。)
    • 那行得通。显然上次我没有正确转换为字符串)。 :)
    【解决方案2】:

    我认为您的流程应该运行良好,您只需将“objectID”转换为String 即可进行比较。使用.toString() 转换_id_user

    如下:

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

    【讨论】:

      猜你喜欢
      • 2016-06-13
      • 2017-04-20
      • 2021-03-03
      • 2019-04-12
      • 2019-12-09
      • 2015-05-02
      • 2015-06-08
      • 2019-05-07
      • 1970-01-01
      相关资源
      最近更新 更多