MongoDB
 sql >> Teknologi Basis Data >  >> NoSQL >> MongoDB

Bagaimana cara membuat Mongoose mendaftar semua dokumen dalam koleksi? Untuk mengetahui apakah koleksinya kosong?

Saya berasumsi setiap pengaturan lain yang diperlukan untuk luwak sudah benar.

Pada baris di bawah, saya rasa 'myField' tidak diperlukan.

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

Ini sesuatu yang lebih dari awal, mungkin ini akan membantu Anda melacak kembali langkah Anda:

 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;



  1. Redis
  2.   
  3. MongoDB
  4.   
  5. Memcached
  6.   
  7. HBase
  8.   
  9. CouchDB
  1. Perintah gagal dengan kesalahan 168 (InvalidPipelineOperator):'Ekspresi tidak dikenal '$match'

  2. Hubungkan ke mongodb yang berjalan di dalam Docker

  3. Meteor - collection.find() selalu mengembalikan semua bidang

  4. Bagaimana cara mengonfigurasi MongoDB saya untuk mempertimbangkan UTF-8?

  5. Haruskah saya mengakses mongodb secara langsung?