javascript - 从 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 并从中获取数据!谁能帮我?谢谢
解决方案
看起来您的连接方式不正确。快速入门指南在这里:
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
我建议为您使用的版本制作快速入门指南。
推荐阅读
- r - 来自向量的动态矩阵
- sql - SCCM 的 SQL 查询
- javascript - 将鼠标悬停在 WordPress 的帖子上时,我想更改底部链接
- blazor - 通过使用应用程序覆盖 blazor 组件库中的隔离 css
- java - android studio中此日志消息的原因是什么
- django - 按 ForeignKey 的字段过滤不同的查询集
- flutter - 使用日历颤振的 Tindercard 刷卡
- java - 如何在 ATG 的列表值中添加逗号
- ios - 如何在 Collectionview Swift 中水平显示特定的部分单元格/项目
- python - 如何将用户输入存储在 tkinter 的列表中?