【问题标题】:How to get the same query with Mongoose as mongodb db.<collection>.find()?如何使用 Mongoose 获得与 mongodb db.<collection>.find() 相同的查询?
【发布时间】:2018-10-07 23:43:35
【问题描述】:

所以 mongodb 控制台中的 db.cats.find() 给出了这样的结果:

[
  {
    "_id": ObjectId("5b71651978e7d706d3e0a507"),
    "name": "George",
    "age": 11,
    "temperament": "Grouchy",
    "__v": 0
  },
  {
    "_id": ObjectId("5b7186b86bbf270d4a5daa01"),
    "name": "Soros",
    "age": 89,
    "temperament": "Evil",
    "__v": 0
  },
  {
    "_id": ObjectId("5b7194ffef27d50d9eb7464d"),
    "name": "Sminem",
    "age": 15,
    "temperament": "cool",
    "__v": 0
  }
]

而猫鼬

 Cat.find({}, function(err, cats){
if(err){
    console.log("Error");
    console.log(err);
} else {
    console.log(cats);
}
});

给出相同的结果,但带有 [] 括号

[
  {
    _id: "5b71651978e7d706d3e0a507",
    name: "George",
    age: 11,
    temperament: "Grouchy",
    __v: 0
  },
  {
    _id: "5b7186b86bbf270d4a5daa01",
    name: "Soros",
    age: 89,
    temperament: "Evil",
    __v: 0
  },
  {
    _id: "5b7194ffef27d50d9eb7464d",
    name: "Sminem",
    age: 15,
    temperament: "cool",
    __v: 0
  }
]

那么我如何得到相同的,但没有方括号[]?

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

    使用:

    Cat.findOne({}, function(err, cats){
      if(err){
        console.log("Error");
        console.log(err);
      } else {
        console.log(cats);
     }
    });
    

    find 返回一个文档数组,findOne 返回一个文档对象。

    【讨论】:

    • 但是如果没有 [] 括号我怎么能得到所有的猫呢?
    • 您要查找一份还是多份?如果你想拥有多个,那么你必须使用 find ,结果将是一个带括号的数组。如果您想查找一个文档,请使用 findOne,它将返回一个文档对象。
    • 我想要一个这样的 api:jsonplaceholder.typicode.com/posts/1,但现在我意识到它是一个单独的文档。感谢您消除困惑。
    猜你喜欢
    • 2021-03-03
    • 2015-07-22
    • 2020-03-14
    • 2012-07-25
    • 1970-01-01
    • 1970-01-01
    • 2019-08-25
    • 2021-11-12
    • 1970-01-01
    相关资源
    最近更新 更多