亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

MongoDB 和 Node js 中的未定義結果

MongoDB 和 Node js 中的未定義結果

阿晨1998 2022-08-04 16:18:57
我想獲取我的收藏數據,我的收藏已命名,并且是我的數據庫的一部分。studentspool與 mongoDB 的連接工作正常,但返回 。console.log(result.lastname)undefined這是我的文件server.jsvar mongo = require('mongodb');var assert = require('assert');const url = 'mongodb://localhost:27017/';mongo.connect(url, function (err, db) {     if(err) {         console.log("Connection failed");    }    console.log("Connection successfull");    var dbo = db.db("pool");    dbo.collection("students").find({}, function(err, result) {        if (err) throw err;        console.log(result.lastname);        db.close();      });});以及我直接在控制臺中看到的我的收藏中的內容studentsdb.students.find();{ "_id" : ObjectId("5eb1570f2c0167c90cc127fd"), "id" : 0, "lastname" : "Sam", "firstname" : "Sung", "email" : "[email protected]", "phone" : 613295990, "validated" : "Validated", "admin" : true }
查看完整描述

2 回答

?
慕村225694

TA貢獻1880條經驗 獲得超4個贊

根據此鏈接:

https://docs.mongodb.com/manual/reference/method/db.collection.find/


.find()返回一個列表,而不僅僅是一個條目。這意味著即使您的集合有一個條目,它也將作為只有一個條目的列表接收。你必須迭代。所以,試試這個:


var mongo = require('mongodb');

var assert = require('assert');

const url = 'mongodb://localhost:27017/';


mongo.connect(url, function (err, db) {


     if(err) {

         console.log("Connection failed");

    }

    console.log("Connection successfull");


    var dbo = db.db("pool");


    dbo.collection("students").find({}, function(err, result).toArray(function(err, result) {

        if (err) throw err;

        console.log(result.lastname);

        db.close();

      });


});

另一個有用的鏈接 : https://www.w3schools.com/nodejs/nodejs_mongodb_find.asp


查看完整回答
反對 回復 2022-08-04
?
千萬里不及你

TA貢獻1784條經驗 獲得超9個贊

我認為它返回了一個數組,你可以試試:

result[0].lastname


查看完整回答
反對 回復 2022-08-04
  • 2 回答
  • 0 關注
  • 108 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號