此问题是 this one 的后续问题而且我觉得问一个新问题比发表评论和发帖要好。
(TL;DR 他们提供了在插入集合时获取 _id 的解决方案)
我已经尝试过使用 .js bash 脚本或在控制台中它似乎不起作用:
var latest;
db.collec.insert({test:"yes"},function(err,newDoc){
latest = newDoc[0]._id;
});
变量不会改变。在控制台中,命令返回 WriteResult({ "nInserted" : 1 })
但是 latest 仍然是 void,在 js 中它的值和以前一样。
没有 Node.js 有没有办法获取 id?我应该切换到 Node.js 吗?
我的 bash 脚本真的只是 mongo --eval '<my whole javascript>'
最佳答案
你的表达中少了一 block 。
var latest;
db.collec.insert({test:"yes"},function(err,newDoc){
latest = newDoc.ops[0]._id;
});
newDoc
包含来自 mongo 的完整响应。
newDoc.ops
包含插入行的数组。
newDoc.insertedIds
包含插入行的 ID 数组。
另一种解决方案是:
var latest;
db.collec.insert({test:"yes"},function(err,newDoc){
latest = newDoc.insertedIds[0];
});
无需使用 Node.js 即可获取数据。您可以使用 Mongodb 外壳。在运行 Mongo 的系统的命令提示符下键入 mongo
以进入交互式 shell。在那里,运行 Mongo 命令:
> show dbs //will list all databases
> use dbName //will use database called dbName
> show collections //will list all collections within the current database
> db.col.find({test: 'yes'}); //will retrieve document from collection named col where 'test' = 'yes'
整个工作 JavaScript 文件:
var mongodb = require('mongodb').MongoClient;
mongodb.connect('mongodb://localhost:27017/testDb', function(err, db){
var collection = db.collection('collec');
collection.insert({'test': 'yes'}, function(err, results){
console.log(results.ops[0]._id);
db.close();
});
});
可以直接通过_id
查询
var mongodb = require('mongodb').MongoClient;
var ObjectId = require('mongodb').ObjectID;
mongodb.connect('mongodb://localhost:27017/testDb', function(err, db){
var collection = db.collection('collec');
var id = ObjectId('583346693b3b904546ca175d');
collection.find({'_id': id}).toArray(function(err, results){
console.log(results);
db.close();
});
});
关于javascript - 从未调用过 Mongodb 插入回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40660885/