如何使用 Mongoose 从 Mongo 获取数据?

发布于 2024-12-05 03:35:26 字数 972 浏览 1 评论 0原文

使用 mongoose 从 mongo 获取任何数据时遇到问题。连接看起来很好,因为我已经打印出了调试语句。我已经彻底搜索了可能导致此问题的原因,但据我所知,我正在设置架构和集合。

这是我在一个名为 posts.js 的文件中的内容:

var mongoose = require('mongoose');

var db = mongoose.connect('mongodb://localhost:27017/sister', function(err) {
  if (err) throw err;}  //this does not get printed
);

mongoose.connection.on("open", function(){
  console.log("mongodb is connected")}  //this gets printed
);

var Schema = mongoose.Schema;
var thePost = new Schema({
        name : String
});

mongoose.model('post', thePost);
var posts = db.model('post');

posts.find({}, [], function(err, calls) { 
  console.log(err, calls, calls.length);  //prints out: null [] 0
});

为了播种数据,我在 mongo shell 中完成了此操作,它插入一个文档,然后显示 find all 可以找到它:

> randumb = { name : 'emile' };
{ "name" : "emile" }
> db.post.insert(randumb);
> db.post.find({});      
{ "_id" : ObjectId("4e775e8cc24f31883fdafbab"), "name" : "emile" }

Running into problems getting any data out of mongo using mongoose. The connection seems fine as i've got debugging statements that are being printed out. I've searched high and low for what could be causing this but afaik I'm setting up the schema and collections fine.

here's what i have in a file called posts.js:

var mongoose = require('mongoose');

var db = mongoose.connect('mongodb://localhost:27017/sister', function(err) {
  if (err) throw err;}  //this does not get printed
);

mongoose.connection.on("open", function(){
  console.log("mongodb is connected")}  //this gets printed
);

var Schema = mongoose.Schema;
var thePost = new Schema({
        name : String
});

mongoose.model('post', thePost);
var posts = db.model('post');

posts.find({}, [], function(err, calls) { 
  console.log(err, calls, calls.length);  //prints out: null [] 0
});

To seed the data, I've done this in my mongo shell, which inserts a document and then shows that find all can find it:

> randumb = { name : 'emile' };
{ "name" : "emile" }
> db.post.insert(randumb);
> db.post.find({});      
{ "_id" : ObjectId("4e775e8cc24f31883fdafbab"), "name" : "emile" }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

不醒的梦 2024-12-12 03:35:26

尝试更改

var posts = db.model('post');

var posts = mongoose.model('post');

try changing

var posts = db.model('post');

to

var posts = mongoose.model('post');
不念旧人 2024-12-12 03:35:26

为了使其更短,请尝试将:更改

mongoose.model('post', thePost);
var posts = db.model('post');

为:

var posts = mongoose.model('post', thePost);

To keep it even shorter, try and change:

mongoose.model('post', thePost);
var posts = db.model('post');

to:

var posts = mongoose.model('post', thePost);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文