I'm trying to select a document by id
I've tried:
collection.update({ "_id": { "$oid": + theidID } }
collection.update({ "_id": theidID }
collection.update({ "_id.$oid": theidID }}
Also tried:
collection.update({ _id: new ObjectID(theidID ) }
This gives me an error 500...
var mongo = require('mongodb')
var BSON = mongo.BSONPure;
var o_id = new BSON.ObjectID(theidID );
collection.update({ _id: o_id }
None of these work. How to select by _id?
var mongo = require('mongodb');
var o_id = new mongo.ObjectID(theidID);
collection.update({'_id': o_id});
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);
});
});
}
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
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);
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.
/* get id */
const id = request.params.id; // string "5d88733be8e32529c8b21f11"
/* set object id */
const ObjectId = require('mongodb').ObjectID;
/* filter */
collection.update({
"_id": ObjectId(id)
} )
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();
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));
});`
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();
}
}
)
}
})
});
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)
)}()
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
Related
When I use mongoose.connection, models are connected directly with the unique connection.
In this case db1 is only used for querying (not model require). But db2 use 2 models.
How can I connect those models with db2 only?
Thanks for helping
const db1 = mongoose.createConnection("atlasuri").asPromise()
const db2 = mongoose.createConnection("localuri").asPromise()
app.get("/",async(req,res)=>{
const finded = (await db1).collection("users")
await finded.forEach(el=> console.log(el))
res.json(finded)
})
Models
const Criterion1=new mongoose.model('Criterion',new mongoose.Schema({
name:string
}));
const User=new mongoose.model('Criterion',new mongoose.Schema({
name:string
}));
Use createConnection():
const CriterionModel = require('./criterion');
const mongoose = require('mongoose');
const atlasuri = 'mongodb://localhost:27017/so1'; // <== your Atlas URI HERE
const localuri = 'mongodb://localhost:27017/so2';
const conn = mongoose.createConnection(atlasuri);
const conn2 = mongoose.createConnection(localuri);
const Criterion1 = conn.model('Criterion', new mongoose.Schema({
name:String
}));
const users = conn2.model('Criterion', new mongoose.Schema({
name:String
}));
// atlasuri
conn.on('connected', async () => {
const doc = await Criterion1({ // add a document
'name': 'Only in atlasuri'
});
await doc.save((err, doc) => {
if (err) {
console.log('error adding!');
}
});
console.log('Added to atlas');
});
// localuri
conn2.on('connected', async () => {
// add a document
const doc = await users({ // add a document
'name': 'Only in localuri'
});
doc.save((err, doc) => {
if (err) {
console.log('error adding!');
}
});
console.log('Added to local');
});
function handleExit(signal) {
console.log(`Received ${signal}. Shutting down.`);
conn.close();
conn2.close();
process.exit(0);
}
process.on('SIGINT', handleExit);
process.on('SIGQUIT', handleExit);
process.on('SIGTERM', handleExit);
In criterion.js:
const mongoose = require('mongoose');
const CriterionSchema = mongoose.Schema({
name:String
});
module.exports = mongoose.model('Criterion', CriterionSchema);
> I am trying to update a data using updateOne method but i am not able to debug it why it is not working ?
router.post('/edit-category/:slug', async (req,res) =>{
// res.send(req.body.id);
try{
const updatedPost = await Category.updateOne(
{ _id: req.body.id},
{
$set: { title: req.body.title },
$set: { slug: req.body.slug }
}
);
// updatedPost.update((error) => {if(error){console.log("hiiiiiiiii"+error)}});
res.send(updatedPost);
// console.log(updatedPost);
}catch(error){
console.log({message:error})
}
});
Two possibilities:
Check in DB whether the document is there in DB with req.body.id as _id
Try for the below code:
const ObjectId = require('mongodb').ObjectID;
const updatedPost = await Category.updateOne({ _id: ObjectId (req.body.id)}
I am trying to find a specific document with mongoose in my Cosmosdb with this query described below.
const mongoose = require('mongoose');
var ObjectID = require('mongodb').ObjectID
const keys = require('../config/keys');
const Item = mongoose.model('items');
const uploadToBlob = async (containerName, blobName, json, id) => {
console.log('id', id)
Item.findOne({ _id: id }, (foundItem) => {
console.log(foundItem)
});
console.log('here')
Item.findOneAndDelete({ name: blobName });
};
I am successfully able to find the document when querying like this below.
const scanMongo = () => {
Item.find({
_id: {
$gt: ObjectID.createFromTime(Date.now() / keys.mongoPurgeInterval)
}}, (err, foundItems) => {
if(err) {
console.log("Oops", err);
return;
}
foundItems.forEach(item => {
JSON.stringify(item)
const blobName = item.name;
json = "'"+item+"'"
const id = item._id
uploadToBlob(keys.containerName, blobName, json, id);
});
});
}
This is what the object I'm looking for looks like when pulled from the query above.
[ { _id: 5cabd5c6e16288230cba2cf6, name: 'test', value: 1, __v: 0 } ]
For kicks, here my model.
const mongoose = require('mongoose');
const { Schema } = mongoose;
const itemSchema = new Schema({
name: String,
value: Number,
});
mongoose.model('items', itemSchema);
I'm befuddled. Any help would be bawler. Thanks!!!
Yeah, the first parameter is supposed to catch the error.
Item.findOne({ _id: id }, (error, foundItem) => {
console.log(foundItem)
I want to print all documents of "members" collection. I used find() function but it throw error : find() is not a function.
In member_model.js (in models/admin folder):
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var MemberSchema = new Schema({
username: String,
password: String
});
module.exports = mongoose.model('members', MemberSchema);
In index.js (in controllers/admin folder):
const members = require('../../models/admin/member_model');
var Members = new members();
Members.find({}, function (err, resDB) {
assert.equal(err,null);
console.log(json(resDB));
});
I checked connecting to DB, it's still ok.
I also read some other questions but any suitable answer for my problem.
Note more i tested like this :
In auth.js (in controllers/admin folder):
const members = require('../../models/admin/member_model');
var Members = new members();
Members.username = req.body.username;
Members.password = req.body.password;
var refererURL = req.headers.referer;
Members.save((err, resSave) => {
if(err) {
console.log(err);
res.redirect(refererURL);
} else {
console.log('saved');
}
})
Members.find({}, function (err, resDB) {
assert.equal(err,null);
console.log(json(resDB));
});
Members.save() is ok, but Members.find() still error.
Help me what my error is ?
Thanks!
Try the below code:
In member_model.js (in models/admin folder):
Change the below code to :
// module.exports = mongoose.model('members', MemberSchema);
module.exports = {
memberCollection: mongoose.model('members', MemberSchema)
}
In index.js (in controllers/admin folder):
const members = require('../../models/admin/member_model');
members.memberCollection.find({}, function (err, resDB) {
assert.equal(err,null);
console.log(json(resDB));
});
I'm using a node.js and mongodb, and I'm trying to query the database based on the mongo generated ID using the following:
collection.findOne( {_id:doc._id} , function(err, item) {});
I am 100% certain that my doc._id is an exact match to the doc _id that I am looking for in the collection, and yet I get a null response from the db query.
I have tried this using other keys in the document and it returns the document just fine. It's only when I try to use the mongo ID.
The MongoDb is an object not a string. To convert my string I used:
var id = require('mongodb').ObjectID(doc._id);
This converts my string into a mongo ObjectId and matches the _id in the db!
Following is the example which spots the issue:
var mongo = require('mongodb'),
Server = mongo.Server,
Db = mongo.Db,
ObjectID = require('mongodb').ObjectID;
var MongoClient = require('mongodb').MongoClient
//let id = your _id, smth like '6dg27sh2sdhsdhs72hsdfs2sfs'...
var obj_id = new ObjectID('52cbd028e9f43a090ca0c1af');
var justId = '52cbd028e9f43a090ca0c1af'; // <== This will not work
MongoClient.connect('mongodb://127.0.0.1:27017/YourDbName', function(err, db) {
console.log('err' + err);
db.collection('YourCollectionName', function(error, collection) {
//collection.find({_id:justId}),function(err, docs) { // <== This will not work
collection.findOne({_id:obj_id},function(err, docs) {
console.log("Printing docs from Array. count " + JSON.stringify(docs));
});
});
});
Use this:
ObjectId = require('mongodb').ObjectID;
Then when you try to find an object in collection by _id use this:
console.log("find by: "+ id);
database.collection("userRegister").findOne({_id: new ObjectId(id)},
function(err, res) {
if (err) console.log(err);
if(res!=null){
console.log(res)
return false;
}
if(res==null){
callback({'status':_error,'flag':'notexist','message':_userNotExist});
return false;
}
});
First we need to get ObjectID from mongodb library and need to create new instance in following way., so that you will get the ObjectID of string. If your are using es6 in your code this code
import { ObjectID } from 'mongodb';
var emQuery = [
{
$match: {
_id: new ObjectID(tlvaltResult[0].customers.createdBy)
}
},
{
$project: {
_id:1,
emailId:1,
mobile:1
}
}
];
console.log(emQuery,'emQuery');
[ { '$match': { _id: 5ad83ff0b443435298741d3b } },
{ '$project': { _id: 1, emailId: 1, mobile: 1 } } ]
var emResult = await User.getAggregation(emQuery);
console.log(emResult,'emResult');
[ { _id: 5ad83ff0b443435298741d3b,
emailId: 'superAdmin#limitlessmobile.com' } ]
First, ensure you've added all required modules in MongoDB config:
var mongo = require('mongodb'),
Server = mongo.Server,
Db = mongo.Db,
ObjectID = require('mongodb').ObjectID;
var BSON = require('mongodb').BSONPure;
var server = new Server('localhost', 27017, {
auto_reconnect: true
});
var db = new Db('YOUR_DB_NAME', server);
Then, when you try to find an object in collection by _id, use:
//let id = your _id, smth like '6dg27sh2sdhsdhs72hsdfs2sfs'...
var obj_id = BSON.ObjectID.createFromHexString(id);
db.collection("NAME_OF_COLLECTION_WHERE_IS_YOUR_OBJECT", function(error, collection) {
collection.findOne( {_id:obj_id} , function(err, item) {
// console.log ( item.username );
});
});
Hope, this works.