I have a mongoDB on an ec2 instance, I have been able to query a collection called Users successfully.
All of a sudden when I am trying to read the collection via id it returns null.
I logged into the instance and queried the database for users and there exists some orders.
I am using mongoose with the following query in my code
module.exports.readUser = function(id){
return new Promise((resolve,reject) => {
User.findOne({_id: id})
.exec()
.then(rem => {
resolve(rem);
})
.catch(error => {
reject(error.message)
})
})
}
When querying from the shell i use the following, and it works -
db.users.find({_id: ObjectId("5e89be482845434a7da45863")})
The above code should work once I am passing in a valid ObjectId String, but it fails across other collections as well.
You need to convert the id to an ObjectId, which can be simply done with:
const { ObjectId } = require('mongodb');
module.exports.readUser = function(id){
return new Promise((resolve,reject) => {
User.findOne({_id: ObjectId(id)})
.exec()
.then(rem => {
resolve(rem);
})
.catch(error => {
reject(error.message)
})
})
}
To answer why it worked before without using ObjectId ... Maybe you changed how new entries are added (i.e. maybe you had manually set the _id to a string before, but now you don't and the _id is now set automatically, which is an ObjectId by default)?
Related
I am calling this code from the front-end and confirmed that there is a proper db connection and that the Id value is properly passed, and that there is a corresponding value in the database, but for some reason, res is null. What am I missing?
app.get("/api/walletlogin/user/:userId", (req, res) => {
id = req.params.userId
var query = {_id: id}
db.collection("Users").findOne(query, (err, result) => {
if (result) {
console.log(result.userName)
} else {
console.log('No User')
}
})
Here is the front-end call:
axios.get('/api/walletlogin/user/' + accounts)
.then((response) => {
console.log('Logged in With ' + accounts)
router.push('/account')
})
.catch((errors) => {
console.log('Cannot log in')
})
}).catch((err) => {
console.log(err, 'err!!')
})
You could try to convert your id to an objectID.
var ObjectId = require('mongodb').ObjectId;
var id = ObjectId(req.params.userId);
to search by id, you must use the ObjectID class from the mongodb package. Here is an example invented by me, it does not reflect the real work, but I hope it will become clear on it:
const { ObjectID } = require('mongodb');
const id = '5ee4f69bfa0b960de8aec158'; // in your example is req.params.userId
db.collection('users').findOne({ _id: new ObjectID(id)}, (error, result) => {
if (error) {
throw error;
}
console.log(result);
})
I am adding the details of the issue initially encountered in case someone else would experience it in the future. The value that is passed from the front-end is a cryptocurrency address. For some reason, some of the characters passed were upper-case, while the same address had been stored in the database with these same characters as lower case. Thus, one needs to add code to make sure that the case of the letters found in the respective addresses is ignored.
J
I am using the following code to get the details of a user when I pass their id as a parameter:
server.get("/users/:id", (req, res) => {
const itemId = req.params.id;
dbCollection.findOne({ _id: itemId }, (error, result) => {
if (error) throw error;
// return item
res.json(result);
});
});
However, this doesn't seem to work, as whenever I run the code, I get returned with a null value.
My question is not the same as many previously asked questions because I have ObjectId('randomId') as my id, and not a string. How can I fix my code?
req.params.id comes as a string while your _id is an ObjectId so this won't work since MongoDB requires type equality first, you need to cast the value:
const itemId = mongoose.Types.ObjectId(req.params.id);
MongoDB wouldn't consider the "itemId" as a MongoDB id, therefore you need to transform it as shown below:
new mongodb.ObjectId(itemId)
This implies that:
const mongodb = require('mongodb')
As others already said, MongoDB expects _id to be an ObjectID. But if you are searching for ONE item, instead of using findOne use findById, which accepts id as a string.
const { Model } = require('./models'); // Model is your Mongoose Schema
server.get("/users/:id", async (req, res) => {
const { id } = req.params;
// This is the same as Model.findOne({ _id: new ObjectId(id) });
const item = await Model.findById(id);
return res.json(item);
});
I'm trying to get a document from a mongoDB collection by object id while using Socket.io.
As findById() doesn't work here and i cant do find({ "_id" : _id}) i dont know how to proceed.
This gives me back my entire collection on the client side. But i just want one document by the given _id.
The _id arrives on the server side. I have checked.
THanks in advance
io.on('connection', socket => {
console.log('user arrived');
socket.emit('chat-message', 'hello-world');
socket.on('send-chat-id', _id => {
console.log(_id);
const chats = db.collection('chats');
chats.find().toArray(function(error, result) { <------
if (error) {
throw error;
}
socket.emit('chat-messages', result);
});
});
});
Whenever you use findById() you need to convert a parameter being passed in from string (coming from UI) into ObjectId by using below line:
const objectId = new ObjectId(_id)
How can I get the values of the searched objects?
const query = new Parse.Query(Parse.User);
query.equalTo("sexo", "feminino");
query
.find()
.then(results => {
console.log(results.get("username"));
})
.catch(error => {
console.log(error);
});
TypeError: "results.get is not a function"
How to get values of a search query in Parse server ?
Query.find will be able to fetch the results of your queries.
As you can have multiples results, the object that you get is an array of elements
so if you want to display the name of all users of your query you'll have to iterate to display all of your users.
const query = new Parse.Query(Parse.User);
query.equalTo("sexo", "feminino");
query
.find()
.then(results => {
results.forEach(user => {
console.log(user.get("username"))
});
})
.catch(error => {
console.log(error);
});
If you want to have examples of queries click here
Hope my answer help you 😊
I use NodeJS to insert documents in MongoDB. Using collection.insert I can insert a document into database like in this code:
// ...
collection.insert(objectToInsert, function(err){
if (err) return;
// Object inserted successfully.
var objectId; // = ???
});
// ...
How can I get the _id of inserted object?
Is there any way to get the _id without getting latest object inserted _id?
Supposing that in same time a lot of people access the database, I can't be sure that the latest id is the id of object inserted.
A shorter way than using second parameter for the callback of collection.insert would be using objectToInsert._id that returns the _id (inside of the callback function, supposing it was a successful operation).
The Mongo driver for NodeJS appends the _id field to the original object reference, so it's easy to get the inserted id using the original object:
collection.insert(objectToInsert, function(err){
if (err) return;
// Object inserted successfully.
var objectId = objectToInsert._id; // this will return the id of object inserted
});
There is a second parameter for the callback for collection.insert that will return the doc or docs inserted, which should have _ids.
Try:
collection.insert(objectToInsert, function(err,docsInserted){
console.log(docsInserted);
});
and check the console to see what I mean.
As ktretyak said, to get inserted document's ID best way is to use insertedId property on result object. In my case result._id didn't work so I had to use following:
db.collection("collection-name")
.insertOne(document)
.then(result => {
console.log(result.insertedId);
})
.catch(err => {
// handle error
});
It's the same thing if you use callbacks.
I actually did a console.log() for the second parameter in the callback function for insert. There is actually a lot of information returned apart from the inserted object itself. So the code below explains how you can access it's id.
collection.insert(objToInsert, function (err, result){
if(err)console.log(err);
else {
console.log(result["ops"][0]["_id"]);
// The above statement will output the id of the
// inserted object
}
});
if you want to take "_id" use simpley
result.insertedId.toString()
// toString will convert from hex
Mongo sends the complete document as a callbackobject so you can simply get it from there only.
for example
collection.save(function(err,room){
var newRoomId = room._id;
});
You could use async functions to get _id field automatically without manipulating data object:
async function save() {
const data = {
name: "John"
}
await db.collection('users').insertOne(data)
return data
}
Returns (data object):
{
    _id: '5dbff150b407cc129ab571ca',
    name: 'John',
}
Now you can use insertOne method and in promise's result.insertedId
#JSideris, sample code for getting insertedId.
db.collection(COLLECTION).insertOne(data, (err, result) => {
if (err)
return err;
else
return result.insertedId;
});
Similar to other responses, you can grab the variable using async await, es6+ features.
const insertData = async (data) => {
const { ops } = await db.collection('collection').insertOne(data)
console.log(ops[0]._id)
}
Another way to do it in async function :
const express = require('express')
const path = require('path')
const db = require(path.join(__dirname, '../database/config')).db;
const router = express.Router()
// Create.R.U.D
router.post('/new-order', async function (req, res, next) {
// security check
if (Object.keys(req.body).length === 0) {
res.status(404).send({
msg: "Error",
code: 404
});
return;
}
try {
// operations
let orderNumber = await db.collection('orders').countDocuments()
let number = orderNumber + 1
let order = {
number: number,
customer: req.body.customer,
products: req.body.products,
totalProducts: req.body.totalProducts,
totalCost: req.body.totalCost,
type: req.body.type,
time: req.body.time,
date: req.body.date,
timeStamp: Date.now(),
}
if (req.body.direction) {
order.direction = req.body.direction
}
if (req.body.specialRequests) {
order.specialRequests = req.body.specialRequests
}
// Here newOrder will store some informations in result of this process.
// You can find the inserted id and some informations there too.
let newOrder = await db.collection('orders').insertOne({...order})
if (newOrder) {
// MARK: Server response
res.status(201).send({
msg: `Order N°${number} created : id[${newOrder.insertedId}]`,
code: 201
});
} else {
// MARK: Server response
res.status(404).send({
msg: `Order N°${number} not created`,
code: 404
});
}
} catch (e) {
print(e)
return
}
})
// C.Read.U.D
// C.R.Update.D
// C.R.U.Delete
module.exports = router;