【问题标题】:How do I get data out of Mongo using Mongoose?如何使用 Mongoose 从 Mongodb 中获取数据?
【发布时间】:2011-11-20 08:59:09
【问题描述】:

使用 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" }

【问题讨论】:

    标签: mongodb mongoose


    【解决方案1】:

    尝试改变

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

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

    【讨论】:

      【解决方案2】:

      要让它更短,请尝试更改:

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

      到:

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

      【讨论】:

        猜你喜欢
        • 2013-11-06
        • 2019-07-17
        • 2012-02-12
        • 1970-01-01
        • 2020-09-27
        • 1970-01-01
        • 2012-06-04
        • 2020-01-13
        相关资源
        最近更新 更多