首页 > 解决方案 > 从 Mongoose 获取数据

问题描述

const mongoose = require ('mongoose');
var url = "mongodb://localhost:27017/db1"
//connect to mangodb 


mongoose.connect(url, function(err, db) {
    var dbo = db.db("db1");
    var query = { username: "mrkinix" };
    dbo.collection("db1").find(query).toArray(function(err, result) {
      if (err) throw err;
      console.log(result);
      db.close();
    });
});

好吧,我第一次使用 mongoose,当我在 cmd 中使用 node 执行它时,我得到了这个错误:

UnhandledPromiseRejectionWarning: TypeError: db.db is not a function

我想连接到 Mongoose DB 并从中获取数据!谁能帮我?谢谢

标签: javascript

解决方案


看起来您的连接方式不正确。快速入门指南在这里:

https://mongoosejs.com/docs/index.html

根据指南,这是您的连接方式:

const mongoose = require ('mongoose');
var url = "mongodb://localhost:27017/db1"
//connect to mongodb 

mongoose.connect(url)

var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
    // we're connected!
    var Schema = mongoose.Schema;

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

    // find each person with a last name matching 'Ghost', selecting the `name` and `occupation` fields
    Person.findOne({ 'name.last': 'Ghost' }, 'name occupation', function (err, person) {
       if (err) return handleError(err);
       // Prints "Space Ghost is a talk show host".
       console.log('%s %s is a %s.', person.name.first, person.name.last, person.occupation);
    });

});

请注意,从版本 4 到版本 5,mongoose 的 API 似乎发生了一些重大更改。因此,请确保您正在阅读正确版本的文档。

这是 V4 文档:https ://mongoosejs.com/docs/4.x/docs/guide.html

这是 V5 文档:https ://mongoosejs.com/docs/index.html

我建议为您使用的版本制作快速入门指南。


推荐阅读