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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10519432/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 12:38:43  来源:igfitidea点击:

How to do raw mongodb operations in mongoose?

mongodbmongoose

提问by Freewind

I'm asking this because when I write unit tests, I want to drop the test database and insert some initialize data, and also check the data in mongodb in testing. So I need raw operations to mongodb.

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

How to do this in mongoose? What I can do now is just create the connection, and not find any document in mongoose's official site.

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

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

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

But how to:

但是如何:

  1. drop the database
  2. create a collection
  3. write some data to a collection
  4. query a collection
  5. drop a collection
  1. 删除数据库
  2. 创建一个集合
  3. 将一些数据写入集合
  4. 查询集合
  5. 删除一个集合

采纳答案by Jamund Ferguson

See the section on "Driver Access" in the docs: http://mongoosejs.com/

请参阅文档中的“驱动程序访问”部分:http: //mongoosejs.com/

Basically you can get access to the node-mongodb-nativedriver by doing YourModel.collectionand then you can insertor removeor dropor whatever you need.

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

There's not a doc, but with this approach you'll get access to everything in here: https://github.com/mongodb/node-mongodb-native/blob/master/lib/mongodb/collection.js

没有文档,但通过这种方法,您可以访问此处的所有内容:https: //github.com/mongodb/node-mongodb-native/blob/master/lib/mongodb/collection.js

Edit:

编辑:

In your case you may want to skip using mongoose in your test suite and use the node-mongodb-nativedirectly, or even write a simple mongodb shell scriptthat can be run before your tests start.

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

回答by steampowered

You can run mongodb commands using the native NodeJS driver by using mongoose.connection.db. This accesses the NodeJS MongoDB driver, and you don't need to create a mongoose model.

您可以使用本机 NodeJS 驱动程序运行 mongodb 命令mongoose.connection.db。这将访问 NodeJS MongoDB 驱动程序,您无需创建 mongoose 模型

An insert

一个插入

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

An update

更新

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

You can send every command specific to that database using the database connection db reference mongoose.connection.db.

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

This is the mongoose API doc: http://mongoosejs.com/docs/api.html#connection_Connection-db

这是猫鼬 API 文档:http: //mongoosejs.com/docs/api.html#connection_Connection-db

Important: Note some of the options in the NodeJS driver are different than the options in MongoDB shell commands. For example findOneAndUpdate()uses returnOriginalinstead of returnNewDocument. See hereand herefor more on this.

重要提示:请注意 NodeJS 驱动程序中的某些选项与 MongoDB shell 命令中的选项不同。例如findOneAndUpdate()使用returnOriginal代替returnNewDocument. 有关更多信息,请参见此处此处

回答by jitendra rajput

use this to run raw operations in mongoose.

使用它在猫鼬中运行原始操作。

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

回答by 2oppin

Have encountered same trouble, to cleanup DBs after tests, and actual answer only confused because of absence "code blocks", so dig docs/code once more, for others-time-saving purpose posting this ;)

遇到了同样的麻烦,在测试后清理数据库,而实际答案只是因为缺少“代码块”而感到困惑,所以再次挖掘文档/代码,为了其他人节省时间的目的发布这个 ;)

Mongoose collection extends Mongodb collection

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

/* * 部分 collection.js * http://mongoosejs.com/docs/api.html#collection-js*/

接口 CollectionBase 扩展了 mongodb.Collection {

文档:http: //mongodb.github.io/node-mongodb-native/2.1/api/Collection.html

Same goes for the connection:

连接也是如此:

The Connection class exposed by require('mongoose') is actually the driver's NativeConnection class. connection.js defines a base class that the native versions extend. See: http://mongoosejs.com/docs/api.html#drivers-node-mongodb-native-connection-js

require('mongoose') 暴露的Connection类实际上就是驱动的NativeConnection类。connection.js 定义了一个原生版本扩展的基类。请参阅:http: //mongoosejs.com/docs/api.html#drivers-node-mongodb-native-connection-js

So all "RAW" operations can be performed on collection/connection, assuming that you have

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

 var connection = mongoose.connection;

then:

然后:

1.drop the database:

1.删​​除数据库:

connection.dropDatabase()

2.create a collection

2.创建一个集合

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

3.write some data to a collection

3.将一些数据写入集合

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

4.query a collection

4.查询一个集合

that's obviously not a question: findAll, find, aggregate, all allowed (see the Docs)

这显然不是一个问题:findAll、find、aggregate、all allowed(参见文档

5.drop a collection

5.删除一个集合

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

回答by hardyRocks

const mongoose = require('mongoose');
mongoose.connect(uri, options);
var db = mongoose.connection;
db.once('open', function () {
  db.collection('collection').find().toArray(function(err, result){
        console.log(result);
  });
}