我想在mongodb中使用node.js从集合中找到结果。我的代码如下
var MongoClient = require('mongodb').MongoClient;
var assert = require('assert');
MongoClient.connect(url, function(err, db) {
assert.equal(null, err);
console.log("Mongo db Connected correctly to server.");
db.close();
})
MongoClient.connect(url, function(err, db){
collection.findOne({_id:req.body.Id},function(err, docs) {
console.log("Printing docs from Array. count " + JSON.stringify(docs));
});
});
我无法获得所需的结果。未定义获取错误集合。
答案 0 :(得分:0)
尝试将id转换为ObjectId:
var MongoClient = require('mongodb').MongoClient;
var ObjectID = require('mongodb').ObjectID;
var assert = require('assert');
MongoClient.connect(url, function(err, db) {
assert.equal(null, err);
console.log("Mongo db Connected correctly to server.");
db.close();
})
MongoClient.connect(url, function(err, db){
db.collection('collectionName').findOne({_id:new ObjectID(req.body.Id)},function(err, docs) {
console.log("Printing docs from Array. count " + JSON.stringify(docs));
});
});
答案 1 :(得分:0)
您需要定义要查询的集合:
db.collection('CollectionName').findOne({_id: req.body.Id}, function(err, docs) {
console.log("Printing docs from Array. count " + JSON.stringify(docs));
db.close();
});