【问题标题】:findOne mongoose query is not working properlyfindOne mongoose 查询无法正常工作
【发布时间】:2019-06-26 04:55:08
【问题描述】:

我使用 express 来创建这个网络应用程序。 我也有猫鼬模型:

{
  username: { type: String, required: true, unique: true },
  password: { type: String, required: true },
  notes: [{
    name: { type: String, required: true }
  }]
}

当我尝试在数组中查找对象时(注释)->

modelName.findOne({ "notes:" {$elemMatch: {"_id": req.body.id } }})
  .exec()
  .then(result => {
    console.log(result);
  })
  .catch(err => {
    console.log(err);
  });

我得到一个用户的整个模型对象而不是一个注释。 这是我得到的结果:

{
  "_id": "5c51dd8be279e9016716e5b9",
  "username": "user1",
  "password": "",
  "notes": [
    {
      "_id": "5c51dd8be279e901671gagag",
      "name": "name of note1"
    },
    {
      "_id": "5c51ff8be279e901671gagag",
      "name": "name of note"
    },
    {
      "_id": "5c51dd8be2131501671gagag",
      "name": "name of note"
    }
  ]
}

然而,我的期望是收到这样的东西:

{
  "_id": "5c51dd8be279e901671gagag",
  "name": "name of note1"
}

P.S:这不是这个答案Mongoose Mongodb querying an array of objects的重复。我已经尝试使用该问题中的代码,但它并没有解决我的问题

【问题讨论】:

标签: javascript node.js express mongoose postman


【解决方案1】:

findOne() 工作得很好。 findOne() 返回与指定查询匹配的任何文档,而不是文档的一部分。如果您只想要该文档的一部分,则必须将其分成两部分...

modelName.findOne({ "notes": {$elemMatch: {"_id": req.body.id } }})
.exec()
.then(result => {
  // Will get an array of notes whose _id === req.body.id
  const resNote = result.notes.filter(n => n._id === req.body.id);
  console.log(resNote);
})
.catch(err => {
console.log(err);
});

请参阅文档here。如果您注意到,它提到功能“找到一个文档”。

【讨论】:

  • 它必须是“notes”:而不是“notes:”。我试过了,我得到了 CoreMongooseArray []
  • 你的意思是它必须是CoreMongooseArray吗?还是您的意思是“这是一个有趣的问题”。我不是母语人士,很抱歉提出愚蠢的问题)
  • 应该是“notes”:试试上面的代码,result应该是单个文档。 resNote 应该是您想要的对象的数组。
  • 天啊,终于成功了。您的答案是正确的,但是由于过滤器方法中的三个 '===',我收到了空数组。我将其更改为双 '==' 并且它有效。谢谢))
  • 很高兴听到!如果你想使用 ===(它比 == 更安全),你应该能够使用 .toString() 编写过滤器调用,如下所示:result.notes.filter(n => n._id.toString() === req.body.id);
猜你喜欢
  • 2018-04-26
  • 2021-06-15
  • 1970-01-01
  • 2013-06-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多