简体   繁体   English

Node.js通过mongoDB中的ID查找结果

[英]Node.js find result by ID from mongoDB

I am new in Node.js so sorry if this is really stupid question but however I try I can't find the answer. 我是Node.js的新手,很抱歉,如果这是一个非常愚蠢的问题,但是我尝试我找不到答案。

I have some simple code: 我有一些简单的代码:

var express = require("express");
var mongoose = require("mongoose");
var cors = require("cors");

mongoose.connect('mongodb://localhost/simple')

var personSchema = {
    firstName:String,
    lastName:String,
    email:String
}

var Person = mongoose.model('Person', personSchema, 'people')

var app = express();
app.use(cors());

app.get('/people', function (req, res) {
    Person.find(function (err, doc) {
        res.send(doc);
    })
})

app.get('/people/:id', function (req, res) {
    Person.findById(req.params.id, function (err, doc) {
        res.send(doc);
    })
})
app.listen(3000);

This should return some data I insert to mongo DB, while first one /people/ return everything correctly (basicly just return dump of DB) 这应该返回我插入mongo DB的一些数据,而第一个/ people /返回一切正确(基本上只返回DB的转储)

The second one with ID return nothing. 带ID的第二个没有返回。 I try to debug it and I see that inside of function ID is defined correctly, I also used ID which comes from "people" site (something like : 55e028081181bfdd8a7972d2 ), dispite this fact I am not able to get any answer or error. 我尝试调试它,我看到函数ID内部定义正确,我也使用来自“人”网站的ID(类似于: 55e028081181bfdd8a7972d2 ),这个事实我不能得到任何答案或错误。

Is there a chance someone can advise me where can be a problem? 是否有人可以告诉我哪里可能有问题?

It's time this question was debunked, as I myself am very much getting tired of the false responses here. 是时候这个问题被揭穿了,因为我自己已经厌倦了这里的错误回应。

The code as a unit is fine. 代码作为一个单位是好的。 The only problems that can be occuring are that you are sending the wrong things or have the wrong collection addressed, as well as one last issue concerning the _id value itself. 可能出现的唯一问题是您发送错误的内容或处理错误的集合,以及有关_id值本身的最后一个问题。

You need nothing other than "raw" express and mongoose for this to work, as my listing proves: 你需要除了“原始”快递和猫鼬之外的其他任何东西,因为我的列表证明:

var async = require('async'),
    express = require('express'),
    mongoose = require('mongoose'),
    Schema = mongoose.Schema;

mongoose.connect('mongodb://localhost/simple');

var personSchema = new Schema({
  firstName: String,
  lastName: String,
  email: String
});

var Person = mongoose.model( 'Person', personSchema );

var app = express();

mongoose.connection.on('open',function(err) {

  async.series(
    [
      function(callback) {
        Person.remove({},callback);
      },
      function(callback) {
        Person.create({
          firstName: "John",
          lastName: "Doe",
          email: "john.doe@example.com"
        },callback);
      }
    ],
    function(err,results) {
      if (err) throw err;
      console.log(
        "Created and call in URL: %s",
        results[1]._id
      );

      // setup routes

      app.get('/people', function(req,res) {
        Person.find(function(err,docs) {
          res.send(docs)
        });
      });

      app.get('/people/:id', function(req,res) {
        Person.findById(req.params.id,function(err,doc) {
          res.send(doc);
        });
      });

      app.listen(3000);
      console.log("ready");

    }
  );

});

Which gives output like: 这给出了如下输出:

Created and call in URL: 55e0464e66e13f6506e8e38e
ready

So when you call the server on the /people url you get: 所以当你在/people url上调用服务器时,你得到:

[
    {
        "_id":"55e0464e66e13f6506e8e38e",
        "firstName":"John",
        "lastName":"Doe",
        "email":"john.doe@example.com",
        "__v":0
    }
]

As a response. 作为回应。

And when you call with the id as in /people/55e0464e66e13f6506e8e38e then you get: 当你在/people/55e0464e66e13f6506e8e38e使用id调用时,你会得到:

{
    "_id":"55e0464e66e13f6506e8e38e",
    "firstName":"John",
    "lastName":"Doe",
    "email":"john.doe@example.com",
    "__v":0
}

As expected. 正如所料。

So if your application is not working then you are either not sending in what you think you are, or you actually have a String for the _id value in the collection, or it is completely mismatched in the collection or database name. 因此,如果您的应用程序不起作用,那么您要么不发送您认为自己的内容,要么实际上在集合中有_id值的字符串,或者它在集合或数据库名称中完全不匹配。 All urls should work, and if none are working then the latter is the case. 所有网址都应该有效,如果没有工作,那么后者就是这种情况。

In the case of the _id being a string, then the schema is wrong and needs to be: 如果_id是一个字符串,那么架构是错误的,需要:

var personSchema = new Schema({
  _id: String
  firstName: String,
  lastName: String,
  email: String
},{ "_id": false });

Where most importantly, apart from setting the correct type for the _id field in the schema is also the { "_id": false } . 最重要的是,除了为模式中的_id字段设置正确的类型之外,还有{ "_id": false }

This is because you need this to tell mongoose to not attempt to parse the "string" into an ObjectId as it always does by default. 这是因为您需要告诉mongoose 不要尝试将“字符串”解析为ObjectId因为它默认情况下总是如此。

Without that setting a "string" will always fail. 如果没有这个设置,“字符串”将始终失败。

But this listing is the proof of what does work, and also the only change really needed if in fact the _id contains a "string" or other type. 但是这个列表证明了什么是有效的,也是唯一真正需要的变化,如果实际上_id包含“字符串”或其他类型。 So if a Number then both set the schema for _id: Number and also { "_id": false } otherwise the same failure reasons occur. 因此,如果一个Number然后都为_id: Number{ "_id": false }设置了模式,否则会出现相同的失败原因。


For pure silliness then change my listing to : 为了纯粹的愚蠢,然后将我的列表更改为:

var personSchema = new Schema({
  _id: { type: String, default: "55e0464e66e13f6506e8e38e" }, 
  firstName: String,
  lastName: String,
  email: String
},{ "_id": false });

And watch it work every time also. 并且每次都看它工作。

And please also remove the { "_id": false } and watch it fail so it becomes clear why this is required when the _id type is meant to be overridden. 并且还请删除{ "_id": false }并观察它失败,以便明确为什么在要覆盖_id类型时需要这样做。

If you have populated your database from outside mongoose, there's a chance you have changed the type of the _id property. 如果您已从mongoose外部填充数据库,则可能已更改_id属性的类型。 If that's the case try adding _id to your schemma as follows: 如果是这种情况,请尝试将_id添加到您的架构中,如下所示:

var personSchema = {
    firstName:String,
    lastName:String,
    email:String,
    _id:String
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM