繁体   English   中英

如何让猫鼬列出集合中的所有文档? 告诉集合是否为空?

[英]How to get Mongoose to list all documents in the collection? To tell if the collection is empty?

我正在使用MEAN堆栈,并在Mongoose中编写这些方法。 我想知道我在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中间件)来帮助自己进行调试,那将非常有帮助。 请在此处发布您的调试建议

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

在下面的行中,我认为不需要'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; 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM