我问这个是因为当我编写单元测试时,我想删除测试数据库并插入一些初始化数据,并在测试中检查 mongodb 中的数据。所以我需要对 mongodb 进行原始操作。
如何在 Mongoose 中做到这一点?我现在能做的就是创建连接,在mongoose的官网找不到任何文档。
var mongoose = require('mongoose');
mongoose.connect('mongo://localhost/shuzu_test');
// get the connection
var conn = mongoose.connection;
但是如何:
最佳答案
您可以通过 mongoose.connection.db
使用 native NodeJS 驱动程序运行 mongodb 命令。这将访问 NodeJS MongoDB 驱动程序,并且您不需要创建 mongoose 模型。
mongoose.connection.db.collection('userCollection').insert({
username: 'captain1',
firstName: 'Steve',
lastName: 'Rogers',
});
mongoose.connection.db.collection('userCollection').update(
{someFilterProperty: true},
{$set: {
siteId: new mongoose.mongo.ObjectId('56cb91bdc5946f14678934ba'),
hasNewSiteId: true}},
{multi: true});
});
您可以使用数据库连接数据库引用 mongoose.connection.db
发送特定于该数据库的每个命令。
这是 Mongoose API 文档:http://mongoosejs.com/docs/api.html#connection_Connection-db
重要提示:请注意,NodeJS 驱动程序中的某些选项与 MongoDB shell 命令中的选项不同。例如 findOneAndUpdate()
使用 returnOriginal
而不是 returnNewDocument
。见 here和 here了解更多信息。
https://stackoverflow.com/questions/10519432/
相关文章:
javascript - Node.js - 使用 Mongoose 创建关系
mongodb - 有没有限制 mongodb 内存使用的选项?
javascript - 使用 Mongoose 的 .populate() 返回某些字段
mongodb - mongodb可以作为嵌入式数据库使用吗?
mongodb - MongoDB 将写入锁定到什么级别? (或 : what does it me
c# - MongoDB C# 驱动程序 - 忽略绑定(bind)字段
node.js - Mongoose Schema 尚未注册模型