我在这里问过这个问题,但没有一个答案对我有用.
我的代码:
var BSON = require('mongodb').BSONPure;
// value is 544d644cf6eea12336f5e0a1
var object_id = BSON.ObjectID.createFromHexString(req.params.id);
}
// Create GET _id query
collection.find(object_id).toArray(
function (err, data) {
if (!err) {
// 200 OK
return res.status(200).send({success: true, code: 200, count: data.length, results: data});
} else {
// 500 Internal Server (Mongodb)
console.log(err);
return res.status(500).send({success: false, code: 500, error: "Internal Server Error"});
}
Run Code Online (Sandbox Code Playgroud)
我试过通过ObjectId找到五种不同的方法,但没有一种方法可以工作.以上是我最近的尝试.我没有得到Node的结果.在我做的时候在mongo shell里面:
> db.people.find({_id : ObjectId("544d644cf6eea12336f5e0a1")});
{ "_id" : ObjectId("544d644cf6eea12336f5e0a1"), "name" : "Jim", "age" : 24, "job" : "engineer" }
Run Code Online (Sandbox Code Playgroud)
如你所见,我得到了一个结果.我在这里错过了什么?
与mongo shell相同,您需要为find()组成一个查询对象.这是一个例子:
var mongodb = require('mongodb');
var MongoClient = mongodb.MongoClient;
var ObjectId = mongodb.ObjectID;
MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
db.collection('people', function(err, collection) {
collection.find({_id: new ObjectId('544d644cf6eea12336f5e0a1')}).toArray(function(err, docs) {
console.log(docs);
db.close();
});
});
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2307 次 |
| 最近记录: |