我正在尝试开发一个同步服务器(想想:SVN之类),它在一个请求中接受来自客户端的一个或多个文档(JSON字符串)(JS对象的JSON字符串化数组),将它们插入/更新到mongodb并发送一个响应 - 这是一个JSON字符串,包含每个文档的插入/更新状态(以及mongo中的_id等更多信息).
如果它是一个文档,我可以做一个插入/更新,并在其回调中,我可以发送响应.
collection.insert(_data, function(error, result) {
if(error) res.send('error');
else res.send(JSON.stringify({result: result}));
});
Run Code Online (Sandbox Code Playgroud)
但是当我有多个文档时如何做到这一点.我可以在前一个回调中插入/更新一个文档.但我担心,如果我这样做,我最终会得到一个可怕的代码阶梯(我可以在一个函数中执行并递归,是的).
任何帮助将不胜感激.顺便说一下,我正在使用这个驱动程序:http://mongodb.github.io/node-mongodb-native/
注意:我不是在查看批量插入或更新,因为正在处理的每个文档都需要单独处理.有些可能需要插入,有些更新,然后有版本号和同步状态检查等.
这个问题的灵感来自这篇文章但在我的情况下我需要过滤MongoId.是否可以轻松地进行下面的过滤,因为我需要在每条路线中使用它?
app.post('/:mongoId(^[0-9a-fA-F]{24}$)', function(req, res){
// Send query based on mongoId
}
Run Code Online (Sandbox Code Playgroud) 收藏:
[{
_id: 'Foo',
plugs: [
{ type: 'CE', code: 12 },
{ type: 'SH': code: 34 }
]
},{
_id: 'Bar',
plugs: [
{ type: 'T2', code: 23 },
{ type: 'T2': code: 43 }
]
}]
Run Code Online (Sandbox Code Playgroud)
在插头阵列中可能存在具有相同类型的条目。当我进行聚合时,我想按插头类型过滤文档。例如,仅返回包含 T2 类型插头的文档。我怎样才能在 mongodb 中做到这一点?我知道 $in 查询,但这仅适用于简单的值数组。
mongodb mongodb-query aggregation-framework node-mongodb-native
我运行Express 4的使用multer,GridFS的流和猫鼬用MongoDB中,我尝试上传的文件,并将其流式传输到GridFS的.
执行此操作的快速路由定义为:
app.post('/uploadfile', function (req, res) {
console.dir(req.files);
// The mongodb instance created when the mongoose.connection is opened
var db = mongoose.connection.db;
// The native mongo driver which is used by mongoose
var mongoDriver = mongoose.mongo;
// Create a gridfs-stream
var gfs = new Gridfs(db, mongoDriver);
var file = req.files.myFile;
var fileId = new ObjectId();
console.log("Creating WriteStream");
var writeStream = gfs.createWriteStream({
_id: fileId,
filename: file.originalname,
mode: 'w',
content_type: file.mimetype,
metadata: {
id: '123', …Run Code Online (Sandbox Code Playgroud) 长期倾听者,第一次来电。
我正在使用节点驱动程序在 mongo 上执行聚合命令,并且该$out阶段似乎仅在链接某些方法时才会生效。
我想aggregate()用 $out 作为管道的最后阶段进行调用,然后回调。目前,它仅在我链接next()或toArray()令人厌烦的情况下才有效,因为方法签名是聚合(管道,选项,回调)。
为了清楚起见,下面的示例进行了简化。
在这里,我使用回调,$out 不生效(即 newNames 未创建,但回调被执行)。我正在重构几个月前的东西,这之前是有效的(节点驱动程序的版本 2.2.33):
db.collection('names')
.aggregate([
{ $match: {} },
{ $limit: 1 },
{ $out: 'newNames' }
], (err, result) => {
// result is an AggregationCursor
callback();
});
Run Code Online (Sandbox Code Playgroud)
如果我不添加回调而是链接 next() ,则 $out 阶段会生效
db.collection('names')
.aggregate([
{ $match: {} },
{ $limit: 1 },
{ $out: 'newNames' }
])
.next((err, result) => {
// result is null, why? …Run Code Online (Sandbox Code Playgroud) mongodb mongodb-query aggregation-framework node-mongodb-native
直接在MongoDB上运行以下文本搜索没有问题:
db.getCollection('schools').find({
$text:
{
$search: 'some query string',
$caseSensitive: false,
$diacriticSensitive: true
}
}, {score: {$meta: "textScore"}}).sort({score:{$meta:"textScore"}})
Run Code Online (Sandbox Code Playgroud)
但是,当尝试使用本机NodeJS驱动程序运行相同的查询时:
function getSchools(filter) {
return new Promise(function (resolve, reject) {
MongoClient.connect('mongodb://localhost:60001', function(err, client) {
const collection = client.db('schools').collection('schools');
collection.find({
$text:
{
$search: filter,
$caseSensitive: false,
$diacriticSensitive: true
}
}, {score: {$meta: "textScore"}}).sort({score:{$meta:"textScore"}}).toArray(function(err, docs) {
if (err) return reject(err);
resolve(docs);
});
});
});
}
Run Code Online (Sandbox Code Playgroud)
我收到以下错误:
MongoError: must have $meta projection for all $meta sort keys
Run Code Online (Sandbox Code Playgroud)
我在这做错了什么?
full-text-search mongodb node.js mongodb-query node-mongodb-native
这是复制我的问题的一个例子:
我用这样的100万份文件填充我的收藏:
for(i=1; i<=1000000; i++){
if(i%3===0)
db.numbers.insert({_id:i, stuff:"Some data", signUpDate: new Date()});
else
db.numbers.insert({_id:i, stuff:"Some data"});
}
Run Code Online (Sandbox Code Playgroud)
因此,每个第3个文档都有一个signUpDate
我创建了以下索引:
db.numbers.ensureIndex({"signUpDate" : 1});
Run Code Online (Sandbox Code Playgroud)
然后,我使用nodejs有以下非常小的应用程序:
var Db = require('mongodb').Db
, Connection = require('mongodb').Connection
, Server = require('mongodb').Server
, format = require('util').format;
var host = 'localhost';
var port = Connection.DEFAULT_PORT;
console.log("Connecting to " + host + ":" + port);
Db.connect(format("mongodb://%s:%s/test?w=1", host, port), function(err, db) {
var collection = db.collection('numbers');
collection.find({'signedUp': true}, {'_id':1}).limit(100000).toArray(function(err, docs){
console.log(docs.length)
});
});
Run Code Online (Sandbox Code Playgroud)
这很好用.
但是,如果我删除它 .limit(100000),服务器就坐在那里,永远不会响应.
简而言之,我所要做的就是返回一个_id的列表,其中signUpDate不为null(应该有333,000左右)
我很确定问题是mongodb缓存的方式,但我不确定如何解决这个问题?
我在node.js中使用MongoDB
我想要的是在一个集合中插入一个文档.该文档具有唯一的ID,lastAccess字段,用于存储上次访问的日期,以及timesAccessed字段,在创建文档时应设置为0,如果更新则应增加1.
我试过了:
// coll is a valid collection
coll.update(
{user: accountInfo.uid},
{user: accountInfo.uid,
lastAccess: new Date(),
$inc: {timesAccessed: 1},
$setOnInsert: {timesAccessed: 0}
},
{upsert: true, w: 1},
function(err, result) {
if (err) throw err;
console.log("Record upserted as " + result);
});
Run Code Online (Sandbox Code Playgroud)
但节点说:
MongoError: Modifiers and non-modifiers cannot be mixed
Run Code Online (Sandbox Code Playgroud)
什么是巧妙和安全的方法来做到这一点?
对于这个方法
内容.js
const content = await Content.findOne({ _id: articleId })
Run Code Online (Sandbox Code Playgroud)
我像这样进行模拟:
内容.test.js
Content.findOne = jest.fn(() => Promise.resolve({ some: 'content' }))
Run Code Online (Sandbox Code Playgroud)
但是我如何模拟find.toArray()mongo 本机驱动程序使用的方法呢?
const posts = await Content.find({ category: 'foo' }).toArray()
Run Code Online (Sandbox Code Playgroud) 好吧,我想知道如何从特定的 mongodb 集合中获取所有索引。我尝试使用listIndexes,indexes和indexInformation,但这些方法只给我空值(数组和对象),但如果我db.getCollection('truck').getIndexes()在 mongo 终端上执行,这会给我所有索引。
我想这可能是一个错误,但我没有找到任何关于此的信息,所以让我展示我的示例和“Robo 3T”的屏幕截图。
await connection.collection('truck').indexes() // returns []
await connection.collection('truck').listIndexes().toArray() // returns []
await connection.collection('truck').indexInformation() // returns {}
Run Code Online (Sandbox Code Playgroud)
所以……这里发生了什么?为什么这些方法效果不佳?
感谢:D
PS:我正在使用mongodb版本3.5.5:https : //github.com/mongodb/node-mongodb-native