【问题标题】:How to get Mongoose to list all documents in the collection? To tell if the collection is empty?如何让猫鼬列出集合中的所有文档?判断集合是否为空?
【发布时间】:2016-01-06 19:30:00
【问题描述】:

我正在使用 MEAN 堆栈并在 Mongoose 中编写这些方法。我想知道我放在猫鼬模型文件中的内容有什么问题。我想使用 Mongoose 简单地打印出 myModel 集合中所有文档的列表。

myModel.methods.myMethod = function(cb){
  this.model("Bids").find({}, 'myField', function(err, results){
    if (err){console.log(err);return err;}
    console.log("okay");
    console.log(results);
  })
  this.save(cb);
}

另外,我可以在 Mongoose 中编写什么代码来判断 myModel 集合是否为空?


授人以鱼不如授人以渔……

因此,如果您能建议我可以安装哪些调试工具(例如 Express 中间件)来帮助我自己调试,那将非常有帮助。 Please post your debugging suggestions here.

【问题讨论】:

  • find() 的第二个参数是 String?你确定吗?看起来很腥
  • 我从Mongoose docs得到它

标签: javascript node.js mongodb mongoose mean-stack


【解决方案1】:

我假设猫鼬所需的所有其他设置都是正确的。

在下面的行中,我认为不需要'myField'。

  this.model("Bids").find({}, 'myField', function(err, results)

这里有更多从头开始的东西,也许它会帮助你追溯你的步骤:

 var mongoose = require('mongoose');

    //connection to Mongodb instance running on=======
    //local machine or anywhere=========================
    var uri = 'mongodb://localhost:27017/test';
    var connection = mongoose.createConnection(uri);


    //Define Schema==================================
    var Schema = mongoose.Schema;
    var BlogPostSchema = new Schema({
      author: { type: Schema.Types.ObjectId },
      title: String,
      body: String
    });


    //Create model===================================================
    var BlogPostModel = connection.model('BlogPost', BlogPostSchema);


    //function to insert doc into model NOTE "pass in your =======
    //callback or do away with it if you don't need one"=========
    var insertBlogPost = function (doc, callback) {
      
      //here is where or doc is converted to mongoose object
      var newblogPost = new BlogPostModel(doc); 
      
      //save to db
      newblogPost.save(function (err) {

        assert.equal(null, err);
        
        //invoke your call back if any
        callback();
        console.log("saved successfully");
      });
    };


    //function to get all BlogPosts====================================
    var getAllBlogPosts = function (callback) {

    //mongoose get all docs. I think here answers your question directly
      BlogPostModel.find(function (err, results) {
        assert.equal(null, err);
        
        //invoke callback with your mongoose returned result
        callback(results);
      });
    };


    //you can add as many functions as you need.

    //Put all of your methods in a single object interface 
    //and expose this object using module.

    var BlogPostManager = {
        insertBlogPost: insertBlogPost,
        getAllBlogPosts : getAllBlogPosts
    }


    module.exports = BlogPostManager;

【讨论】:

  • 感谢您向我展示此代码,以便我可以检查所有内容。原来我拼错了我的模型的名字。谢谢!
猜你喜欢
  • 1970-01-01
  • 2013-08-19
  • 2014-09-25
  • 2021-12-16
  • 2021-06-03
  • 2019-05-22
  • 2017-11-27
  • 1970-01-01
相关资源
最近更新 更多