如何在猫鼬中进行原始 mongodb 操作? [英] How to do raw mongodb operations in mongoose?

查看:29
本文介绍了如何在猫鼬中进行原始 mongodb 操作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

如何在猫鼬中做到这一点?我现在能做的就是建立连接,在mongoose官网找不到任何文档.

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;

但是如何:

  1. 删除数据库
  2. 创建一个集合
  3. 将一些数据写入集合
  4. 查询集合
  5. 删除一个集合

推荐答案

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

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

基本上,您可以通过执行以下操作来访问 node-mongodb-native 驱动程序YourModel.collection 然后你可以insertremovedrop 或任何你需要的东西.

Basically you can get access to the node-mongodb-native driver by doing YourModel.collection and then you can insert or remove or drop or whatever you need.

没有文档,但通过这种方法,您可以访问此处的所有内容:https://mongoosejs.com/docs/api.html#collection-js

There's not a doc, but with this approach you'll get access to everything in here: https://mongoosejs.com/docs/api.html#collection-js

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

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

这篇关于如何在猫鼬中进行原始 mongodb 操作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆