javascript - findOne Mongoose 查询无法正常工作

标签 javascript node.js express mongoose postman

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

{
  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 。我已经尝试使用该问题中的代码,但它不能解决我的问题

最佳答案

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 。如果您注意到,它提到该功能“查找一个文档”。

关于javascript - findOne Mongoose 查询无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54482451/

相关文章:

javascript - 正则表达式:匹配帐号,但不匹配 token /生日

javascript - 如何检查div是父div的最后一个 child

javascript - 停止在 Javascript 中导入时初始化模块

javascript - 如何限制用户访问 ExpressJS/NodeJS 中的静态 html 文件?

javascript - 不确定如何在 Express/MongoDB 应用程序中处理数据访问对象/层

javascript - html 表中可编辑字段的更改事件仅影响顶行计算字段

node.js - npm install mongoose : shasums. txt 丢失

node.js - Express 找不到静态文件

javascript - JS 中处理 Object 的嵌套属性

javascript - Node.js Express 不能使用路由