Js mongodb select document by_id node-mongodb-national

我试图通过 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 }

这些都不起作用。如何选择 by _ id?

124617 次浏览
var mongo = require('mongodb');
var o_id = new mongo.ObjectID(theidID);
collection.update({'_id': o_id});

With native_parser:false:

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

With native_parser:true:

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

This the approach that worked for me.

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);
});
});
}

The answer depends upon the variable type you are passing in as the id. I pulled an object id by doing a query and storing my account_id as the ._id attribute. Using this method you simply query using the 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();
}
}
)
}
})

});

now you can just use this:

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

You can see documentation here

I just used this code in Node.js app in controller file, and it works:

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

do not forget to install "mongodb" before, and if you are using encryption of your passwords with bcrypt with "presave", be sure that you will not encrypt password after each modification of the record in DB.

This is what worked for me. Using mongoDB

const mongoDB = require('mongodb')

Then at the bottom where I am making my express get call.

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));


});`
/* get id */
const id        = request.params.id; // string "5d88733be8e32529c8b21f11"


/* set object id */
const ObjectId  = require('mongodb').ObjectID;


/* filter */
collection.update({
"_id": ObjectId(id)
} )

If you use Mongosee, you can simplify the function

FindById:

this replace in mongodb: "_id" : ObjectId("xyadsdd434434343"),

example:


// find adventure by id and execute
Adventure.findById('xyadsdd434434343', function (err, adventure) {});

https://mongoosejs.com/docs/api.html#model_Model.findById

I'm using client "mongodb": "^3.6.2" and server version 4.4.1

// where 1 is your document id
const document = await db.collection(collection).findOne({ _id: '1' })
console.log(document)

If you want to copy and paste here's all you need.

const { MongoClient } = require('mongodb')
const uri = '...'
const mongoDb = '...'
const options = {}
;(async () => {
const client = new MongoClient(uri, options)
await client.connect()
const db = client.db(mongoDb)
const document = await db.collection(collection).findOne({ _id: '1' })
console.log(document)
)}()

ObjectId reports deprecated when called inside find() function in "mongodb": "^4.1.2" if the ObjectId is imported like this

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

instead, when I import it with named import there is no deprecated warning

const { MongoClient, ObjectId } = require("mongodb");

then I can call it regularly

const findResult = await collection.find({_id: ObjectId(id)}).toArray();

In Mongoose, the Model.findById() function is used to find one document by its _id. The findById() function takes in a single parameter, the document id. It returns a promise that resolves to the Mongoose document if MongoDB found a document with the given id, or null if no document was found.

const schema = new mongoose.Schema({ _id: Number }, { versionKey: false });
const Model = mongoose.model('MyModel', schema);


await Model.create({ _id: 1 });


// `{ _id: 1 }`
await Model.findById(1);


// `null` because no document was found
await Model.findById(2);

When you call findById(_id), Mongoose calls findOne({ _id }) under the hood. That means findById() triggers findOne() middleware.

const schema = new mongoose.Schema({ _id: Number }, { versionKey: false });
schema.pre('findOne', function() {
console.log('Called `findOne()`');
});
const Model = mongoose.model('MyModel', schema);
await Model.create({ _id: 1 });


// Prints "Called `findOne()`" because `findById()` calls `findOne()`
await Model.findById(1);

Mongoose casts queries to match your schema. That means if your _id is a MongoDB ObjectId, you can pass the _id as a string and Mongoose will convert it to an ObjectId for you.

const _id = '5d273f9ed58f5e7093b549b0';
const schema = new mongoose.Schema({ _id: mongoose.ObjectId }, { versionKey: false });
const Model = mongoose.model('MyModel', schema);


await Model.create({ _id: new mongoose.Types.ObjectId(_id) });


typeof _id; // 'string'
// `{ _id: '5d273f9ed58f5e7093b549b0' }`
const doc = await Model.findById(_id);


typeof doc._id; // 'object'
doc._id instanceof mongoose.Types.ObjectId; // true

Source