簡體   English   中英

貓鼬查找同時執行if和else語句的回調函數

[英]Mongoose find callback function executing both if and else statements

我是貓鼬和Node的新手,但這是我的頁面上顯示一個露營地的路線。 由於某種原因,findById的回調函數同時在下面的if和else語句中運行。 因此,我的代碼可以找到正確的對象並將其顯示在瀏覽器中,但是它似乎還返回了未定義的對象。

另外,當我在回調函數中使用console.log(camp.name)時,它拋出一個錯誤,並說它無法引用undefined的name屬性...因此,即使它確實找到了未定義的對象,它似乎仍在引用某些未定義的對象。我正在尋找的對象。

app.get("/campgrounds/:id",function(req, res){
    var camp_Id = req.params.id;
    console.log("ID type: "+ typeof(camp_Id) + " | "+camp_Id);

    var camps = Campground.findById(camp_Id, function(err,camp){
        console.log(camp);

        if (err){
            console.log(err);
        }
        else{
            res.render("show", {camp:camp});
        }
    });
});

這是控制台輸出:

ID type: string | 5a80c8c54d30a717de9121f4
{ _id: 5a80c8c54d30a717de9121f4,
  name: 'Fire Camp',
  image: 'https://images.unsplash.com/photo-1496379590766-6732d042fef5?ixlib=rb-0.3.5&ixid=eyJhcHBfaWQiOjEyMDd9&s=65f8c4aa65a833e229c48dd9d3c2f12d&auto=format&fit=crop&w=1350&q=80',
  description: 'Fire and Camps and stuff. Best for smores.',
  __v: 0 }
ID type: string | campgrounds.js
undefined
{ CastError: Cast to ObjectId failed for value "campgrounds.js" at path "_id" for model "Campground"
    at MongooseError.CastError (/home/ec2-user/environment/YelpCamp/node_modules/mongoose/lib/error/cast.js:27:11)
    at ObjectId.cast (/home/ec2-user/environment/YelpCamp/node_modules/mongoose/lib/schema/objectid.js:158:13)
    at ObjectId.SchemaType.applySetters (/home/ec2-user/environment/YelpCamp/node_modules/mongoose/lib/schematype.js:701:12)
    at ObjectId.SchemaType._castForQuery (/home/ec2-user/environment/YelpCamp/node_modules/mongoose/lib/schematype.js:1072:15)
    at ObjectId.castForQuery (/home/ec2-user/environment/YelpCamp/node_modules/mongoose/lib/schema/objectid.js:198:15)
    at ObjectId.SchemaType.castForQueryWrapper (/home/ec2-user/environment/YelpCamp/node_modules/mongoose/lib/schematype.js:1041:15)
    at cast (/home/ec2-user/environment/YelpCamp/node_modules/mongoose/lib/cast.js:273:32)
    at Query.cast (/home/ec2-user/environment/YelpCamp/node_modules/mongoose/lib/query.js:3133:12)
    at Query._castConditions (/home/ec2-user/environment/YelpCamp/node_modules/mongoose/lib/query.js:1269:10)
    at Query._findOne (/home/ec2-user/environment/YelpCamp/node_modules/mongoose/lib/query.js:1485:8)
    at /home/ec2-user/environment/YelpCamp/node_modules/kareem/index.js:276:8
    at /home/ec2-user/environment/YelpCamp/node_modules/kareem/index.js:23:7
    at _combinedTickCallback (internal/process/next_tick.js:73:7)
    at process._tickCallback (internal/process/next_tick.js:104:9)
  message: 'Cast to ObjectId failed for value "campgrounds.js" at path "_id" for model "Campground"',
  name: 'CastError',
  stringValue: '"campgrounds.js"',
  kind: 'ObjectId',
  value: 'campgrounds.js',
  path: '_id',
  reason: undefined,
  model: 
   { [Function: model]
     hooks: Kareem { _pres: [Object], _posts: [Object] },
     base: 
      Mongoose {
        connections: [Object],
        models: [Object],
        modelSchemas: [Object],
        options: [Object],
        _pluralize: [Function: pluralize],
        plugins: [Object] },
     modelName: 'Campground',
     model: [Function: model],
     db: 
      NativeConnection {
        base: [Object],
        collections: [Object],
        models: [Object],
        config: [Object],
        replica: false,
        hosts: null,
        host: 'localhost',
        port: 27017,
        user: null,
        pass: null,
        name: 'YelpCamp',
        options: null,
        otherDbs: [],
        states: [Object],
        _readyState: 1,
        _closeCalled: false,
        _hasOpened: true,
        _listening: false,
        _connectionOptions: [Object],
        '$initialConnection': [Object],
        db: [Object],
        client: [Object] },
     discriminators: undefined,
     '$appliedMethods': true,
     '$appliedHooks': true,
     schema: 
      Schema {
        obj: [Object],
        paths: [Object],
        aliases: {},
        subpaths: {},
        virtuals: [Object],
        singleNestedPaths: {},
        nested: {},
        inherits: {},
        callQueue: [],
        _indexes: [],
        methods: {},
        statics: {},
        tree: [Object],
        query: {},
        childSchemas: [],
        plugins: [Object],
        s: [Object],
        _userProvidedOptions: undefined,
        options: [Object],
        '$globalPluginsApplied': true,
        _requiredpaths: [] },
     collection: 
      NativeCollection {
        collection: [Object],
        opts: [Object],
        name: 'campgrounds',
        collectionName: 'campgrounds',
        conn: [Object],
        queue: [],
        buffer: false,
        emitter: [Object] },
     Query: { [Function] base: [Object] },
     '$__insertMany': [Function],
     '$init': Promise { [Object], catch: [Function] } } }

編輯:這是從我的角度來看的代碼:campgrounds.ejs:

<% for(var i=0; i < camps.length; i++){     %>

            <div class = "col-md-4 col-sm-6">
                <a href="/campgrounds/<%=camps[i].id%>">
                <div class = "img-thumbnail">
                    <img class="img-fluid" src="<%=camps[i]["image"]%>" alt="<%=camps[i]["name"]%>">
                    <div class="caption text-center"><%= camps[i]["name"] %></div>
                </div>
                </a>
            </div>

        <%    };    %>

看起來您正在發出兩個請求,一個是對“ / campgrounds / 5a80c8c54d30a717de9121f4”的請求,它們找到了正確的對象,另一個是對“ /campgrounds/campgrounds.js”的返回未定義的請求。

您的錯誤可能在您看來,只需查看ID的第二個日志即可:

ID type: string | campgrounds.js ID type: string | campgrounds.js

之后,貓鼬告訴您ID為campground.js時失敗:

'Cast to ObjectId failed for value "campgrounds.js" at path "_id"

您可能正在使用campgrounds.js作為ID來呼叫路線。

這應該從

Campground.findById(camp_Id, function(err,camp){

Campground.findById(new mongoose.Types.ObjectId(camp_Id), function(err,camp){

問題是您試圖在此路由中傳遞:id。 如果您有一條路線,例如“ campgrounds / xyz”,該路線位於“ campgrounds /:id”路線下。 然后它將“ xyz”視為:id並嘗試呈現此頁面。

嘗試在所有其他路線下放置“ campgroungs /:id”路線代碼段,然后檢查

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM