首页 文章

如何在猫鼬中进行原始mongodb操作?

提问于
浏览
51

我问这个是因为当我编写单元测试时,我想删除测试数据库并插入一些初始化数据,并在测试中检查mongodb中的数据 . 所以我需要mongodb的原始操作 .

如何在猫鼬中做到这一点?我现在能做的就是创建连接,而不是在mongoose的官方网站上找到任何文件 .

var mongoose = require('mongoose');
 mongoose.connect('mongo://localhost/shuzu_test');

 // get the connection
 var conn = mongoose.connection;

但是如何:

  • 删除数据库

  • 创建一个集合

  • 将一些数据写入集合

  • 查询集合

  • 删除一个集合

4 回答

  • 41

    用它来运行mongoose中的原始操作 .

    Model_name.collection.insertMany(array, { ordered: false },function(err, success){
                console.log(success);
            });
    
  • 1

    遇到同样的麻烦,在测试后清理数据库,实际答案因为缺席而混淆"code blocks",所以再次挖掘文档/代码,为其他人节省时间用于发布此内容;)

    Mongoose系列扩展了Mongodb系列

    / * * section collection.js * http://mongoosejs.com/docs/api.html#collection-js * / interface CollectionBase extends mongodb.Collection {Documentation:http://mongodb.github.io/node-mongodb -native / 2.1 / API / Collection.html

    同样适用于连接:

    require('mongoose')公开的Connection类实际上是驱动程序的NativeConnection类 . connection.js定义了本机版本扩展的基类 . 请参阅:http://mongoosejs.com/docs/api.html#drivers-node-mongodb-native-connection-js

    所以所有“RAW”操作都可以在收集/连接上执行,假设你有

    var connection = mongoose.connection;
    

    然后:

    1.drop the database:

    connection.dropDatabase()
    

    2.create a collection

    connection.collection('newcollection') // creates if not exists
    

    3.write some data to a collection

    connection.collection('mybenotnewcollection').bulkWrite([
      { insertOne: { whatewer: { you: 'need' } } },
    ]);
    

    4.query a collection

    这显然不是一个问题:findAll,find,aggregate,all allowed(参见Docs

    5.drop a collection

    connection.collection('notsonewcollection').drop()
    
  • 36

    请参阅文档中的"Driver Access"部分:http://mongoosejs.com/

    基本上你可以通过 YourModel.collection 访问node-mongodb-native驱动程序然后你可以 insertremovedrop 或任何你需要的 .

    有's not a doc, but with this approach you' ll可以访问这里的所有内容:https://github.com/mongodb/node-mongodb-native/blob/master/lib/mongodb/collection.js

    Edit:

    在您的情况下,您可能希望跳过在测试套件中使用mongoose并直接使用node-mongodb-native,或者甚至编写一个可以在测试开始之前运行的简单mongodb shell script .

  • 3

    您可以使用 mongoose.connection.db 运行本机mongodb命令 . 这将访问本机MongoDB驱动程序和 you don't need to create a model .

    插入

    mongoose.connection.db.collection('userCollection').insert({
      username: 'user1',
      firstName: 'Steve',
      lastName: 'LastName', 
    });
    

    更新

    mongoose.connection.db.collection('userCollection').update(
      {someFilterProperty: true},
      {$set: {
         siteId: new mongoose.mongo.ObjectId('56cb91bdc5946f14678934ba'),
         hasNewSiteId: true}},
      {multi: true});
    });
    

    您可以使用数据库连接db reference mongoose.connection.db 发送特定于该数据库的每个命令 .

    这是mongoose API doc:http://mongoosejs.com/docs/api.html#connection_Connection-db

相关问题