簡體   English   中英

MongoDB collection.findOne() 返回未定義的值

[英]MongoDB collection.findOne() returns undefined value

const Location = require("../models/locations");

getLocation = async(req, res) => {
   await Location.findOne(
    { name: req.query.locationName },     // req.query.locationName is "Gurgaon"
    { restaurantIds: 1 },
    (err, location) => {
      if (err) throw err;
      else {
        console.log(location);
        /*
               {
                   _id: 6004f9cff6ae9921f89f0f81,
                   restaurantIds: [ 6004fb53f6ae9921f89f0f83, 600792321b229bae25a66497 ]
               }
        */
        console.log(location._id);    // 6004f9cff6ae9921f89f0f81
        console.log(location.restaurantIds);     // undefined
        return location;
      }
    }
  );
}

module.exports = { getLocation };

output截圖

這就是位置集合的樣子。

{
  "_id" : ObjectId("6004f9cff6ae9921f89f0f81"),
  "name" : "Gurgaon",
  "restaurantIds" : [
          ObjectId("6004fb53f6ae9921f89f0f83"),
          ObjectId("600792321b229bae25a66497")
  ]
}

這是位置架構。

const mongoose = require("mongoose");
const Schema = mongoose.Schema;

const Locations = new Schema({}, { strict: false });

module.exports = mongoose.model("locations", Locations);

我不知道 location.restaurantIds 返回我未定義的原因。 請幫我解決一下這個。 我是 mongodb 的新手。

有一些原因可能是您沒有在 mongoose 架構中指定此字段,嘗試在您的架構中添加字段,您就可以在查詢中訪問此字段。


第二個選項,如果您不想在架構中指定該字段,請嘗試lean()

默認情況下,ZCCADCDEDB567ABAE643E15DCF0974E503Z 查詢返回 ZCCADCDEDB567ABAE643E15DCF0974E503Z 文檔 class 的實例。 啟用精益選項會告訴 ZCCADCDEDB567ABAE643E15DCF0974E503Z 跳過實例化完整的 ZCCADCDEDB567ABAE643E15DCF0974E503Z 文檔,只給你 POJO。

await Location.findOne(.. your query).lean();

restaurantIds 是一個嵌套的 object,你必須填充它:

const Location = require("../models/locations");

getLocation = async(req, res) => {
   await Location.findOne(
    { name: req.query.locationName },   
    { restaurantIds: 1 })
    .populate('restaurantIds').then(location => {
        console.log(location);
        console.log(location._id);   
        console.log(location.restaurantIds);
        return location;
        })
        .catch(err => {
            throw err;
        })
  );
}

module.exports = { getLocation };

看起來你的restaurantIds是一個數組,所以當你打印它時,你必須使用數組。 從改變開始:

console.log(location.restaurantIds);

至:

console.log(location.restaurantIds[0]);

在此示例中,您將打印數組中的第一個 object,並在代碼中將其用作數組,就可以了。

編輯:添加restaurantIds后,現在我們知道它是 ObjectID 的數組,這種數組無法打印。

暫無
暫無

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

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