MongoDB 和 Node js 中的未定义结果

我想获取我的收藏数据,我的收藏已命名,并且是我的数据库的一部分。studentspool


与 mongoDB 的连接工作正常,但返回 。console.log(result.lastname)undefined


这是我的文件server.js


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) {

        if (err) throw err;

        console.log(result.lastname);

        db.close();

      });


});

以及我直接在控制台中看到的我的收藏中的内容studentsdb.students.find();


{ "_id" : ObjectId("5eb1570f2c0167c90cc127fd"), "id" : 0, "lastname" : "Sam", "firstname" : "Sung", "email" : "sc@mail.com", "phone" : 613295990, "validated" : "Validated", "admin" : true }


阿晨1998
浏览 121回答 2
2回答

慕村225694

根据此链接: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

千万里不及你

我认为它返回了一个数组,你可以试试:result[0].lastname
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript