Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/371.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/github/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript node.js mongodb按_idnode mongodb native选择文档_Javascript_Mongodb_Node.js - Fatal编程技术网

Javascript node.js mongodb按_idnode mongodb native选择文档

Javascript node.js mongodb按_idnode mongodb native选择文档,javascript,mongodb,node.js,Javascript,Mongodb,Node.js,我正在尝试按id选择文档 我试过: collection.update({ "_id": { "$oid": + theidID } } collection.update({ "_id": theidID } collection.update({ "_id.$oid": theidID }} 还尝试: collection.update({ _id: new ObjectID(theidID ) } 这给了我一个错误500 var mongo = require('mongodb')

我正在尝试按id选择文档

我试过:

collection.update({ "_id": { "$oid": + theidID } }

collection.update({ "_id": theidID }

collection.update({ "_id.$oid": theidID }}
还尝试:

collection.update({ _id: new ObjectID(theidID ) }
这给了我一个错误500

var mongo = require('mongodb')
var BSON = mongo.BSONPure;
var o_id = new BSON.ObjectID(theidID );

collection.update({ _id: o_id }

这些都不管用。如何通过_id进行选择?

使用
本机\u解析器:false

var mongo = require('mongodb');
var o_id = new mongo.ObjectID(theidID);
collection.update({'_id': o_id});
var BSON = require('mongodb').BSONPure;
var o_id = BSON.ObjectID.createFromHexString(theidID);
使用
本机\u解析器:true

var BSON = require('mongodb').BSONNative;
var o_id = BSON.ObjectID.createFromHexString(theidID);

这就是对我有效的方法

var ObjectId = require('mongodb').ObjectID;

var get_by_id = function(id, callback) {
  console.log("find by: "+ id);
  get_collection(function(collection) {
    collection.findOne({"_id": new ObjectId(id)}, function(err, doc) {
       callback(doc);
    });
  });
}

答案取决于作为id传入的变量类型。我通过执行查询并将我的帐户id存储为。\ id属性来提取对象id。使用此方法,您只需使用mongo id进行查询

// begin account-manager.js
var MongoDB   = require('mongodb').Db;
var dbPort      = 27017;
var dbHost      = '127.0.0.1';
var dbName      = 'sample_db';
db = new MongoDB(dbName, new Server(dbHost, dbPort, {auto_reconnect: true}), {w: 1});
var accounts = db.collection('accounts');

exports.getAccountById = function(id, callback)
{ 
  accounts.findOne({_id: id},
    function(e, res) {  
    if (e) {
        callback(e)
    }
    else {
        callback(null, res)
    }

  });
}
// end account-manager.js

// my test file
var AM = require('../app/server/modules/account-manager');

it("should find an account by id", function(done) {

AM.getAllRecords(function(error, allRecords){
  console.log(error,'error')
  if(error === null) {
    console.log(allRecords[0]._id)
    // console.log('error is null',"record one id", allRecords[0]._id)
    AM.getAccountById(          
      allRecords[0]._id,
      function(e,response){
        console.log(response,"response")
        if(response) {
          console.log("testing " + allRecords[0].name + " is equal to " + response.name)
          expect(response.name).toEqual(allRecords[0].name);
          done();    
        } 
      }
    )  
  } 
})

}))

现在,您可以使用以下功能:

var ObjectID = require('mongodb').ObjectID;
var o_id = new ObjectID("yourObjectIdString");
....
collection.update({'_id': o_id});

您可以查看文档

我刚刚在控制器文件的Node.js应用程序中使用了这段代码,它可以工作:

var ObjectId = require('mongodb').ObjectId;
...
User.findOne({_id:ObjectId("5abf2eaa1068113f1e")})
.exec(function(err,data){
   // do stuff
})

请不要忘记安装“mongodb”,如果您使用bcrypt和“presave”对密码进行加密,请确保每次修改DB中的记录后都不会对密码进行加密。

这对我很有效。 使用mongoDB

const mongoDB=require('mongoDB')

然后在底部,我在那里做我的快速得到电话

router.get('/users/:id', (req, res) => {
const id = req.params.id;
var o_id = new mongoDB.ObjectID(id);

const usersCollection = database.collection('users');

usersCollection.findOne({
  _id: o_id
})

.then(userFound => {
  if (!userFound){
    return res.status(404).end();
  }
  // console.log(json(userFound));
  return res.status(200).json(userFound)
})
.catch(err => console.log(err));

 });`

如果使用Mongosee,可以简化函数

FindById:

这在mongodb中被替换为:
“\u id”:ObjectId(“xyadd4344343”),

我正在使用客户端
“mongodb”:“^3.6.2”
和服务器版本
4.4.1

// where 1 is your document id
const document = await db.collection(collection).findOne({ _id: '1' })
console.log(document)
如果你想复制和粘贴这里的所有你需要的

const{MongoClient}=require('mongodb')
常量uri='…'
常量mongoDb=“…”
常量选项={}
;(异步()=>{
const client=new MongoClient(uri,选项)
等待client.connect()
const db=client.db(mongoDb)
const document=await db.collection(collection).findOne({u id:'1'})
console.log(文档)
)}()

collection.find({“\u id”:ObjectId(theidID)})
应该可以用。@Bugai13我放弃了,最后为每个文档分配了一个自定义id。我需要这个来进行选择/查找(甚至不是更新)。运气好吗?如果没有对正确的序列化程序的引用,该方法将不起作用。@Berniehakett此方法不适用于mongodb 3.4版的节点运行时12.13。它给出了此处描述的2016年的错误-仍然可以正常工作。如果没有maby,您有
原生语法分析器:false
——请检查下面的Raphael回复。确保您在
require('mongodb')
上调用
ObjectID()
,而不是在
require('mongodb')上调用。通过这种方式,我得到了
MongoClient.ObjectID不是一个构造函数
错误。经过2小时的尝试,最后我用您的答案确定了它,非常感谢。2021年,仍然有效。
example:

// find adventure by id and execute
Adventure.findById('xyadsdd434434343', function (err, adventure) {});
// where 1 is your document id
const document = await db.collection(collection).findOne({ _id: '1' })
console.log(document)