Mongo DB is not updated by id - javascript

i'm trying to update mongo db document with mongo db driver on node js, the log show that it's updated but the data is not updated, i'm trying to get the data to get updated with id document and the document is not updated, but when i use another field as a variable to search the document, the document is updated.
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://192.168.1.200:27017/";
MongoClient.connect(url, function(err, db) {
if (err) throw err;
var dbo = db.db("monitoring");
var myquery = { _id : "62e5e171f38e161d6e905772" };
var newvalues = { $set: { status: "1" } };
dbo.collection("hosts").updateOne(myquery, newvalues, function(err, res) {
if (err) throw err;
console.log("1 document updated");
db.close();
});
});
Picture of the data:

_id property in MongoDB is not of type String, it's of type ObjectId. Try this:
const ObjectID = require('mongodb').ObjectID;
...
const myquery = { _id : new ObjectId("62e5e171f38e161d6e905772") };

Related

I have to delete the product from the database of mongodb by nodejs and javascript how to do in this case [duplicate]

Why I can't remove record by _id?
Code:
db.collection('posts', function(err, collection) {
collection.remove({_id: '4d512b45cc9374271b00000f'});
});
You need to pass the _id value as an ObjectID, not a string:
var mongodb = require('mongodb');
db.collection('posts', function(err, collection) {
collection.deleteOne({_id: new mongodb.ObjectID('4d512b45cc9374271b00000f')});
});
MongoDb has now marked the remove method as deprecated. It has been replaced by two separate methods: deleteOne and deleteMany.
Here is their relevant getting started guide: https://docs.mongodb.org/getting-started/node/remove/
and here is a quick sample:
var mongodb = require('mongodb');
db.collection('posts', function(err, collection) {
collection.deleteOne({_id: new mongodb.ObjectID('4d512b45cc9374271b00000f')}, function(err, results) {
if (err){
console.log("failed");
throw err;
}
console.log("success");
});
});
With TypeScript, you can to it using imports, instead of requiring the whole library
import { ObjectID } from 'mongodb'
db.collection('posts', function(err, collection) {
collection.deleteOne({_id: new ObjectID('4d512b45cc9374271b00000f')});
});
First include mongodb
var mongodb = require("mongodb");
You have to include the ObjectID from mongodb
var ObjectID = require('mongodb').ObjectID;
Then Use
var delete_id = request.params.id;//your id
collection.deleteOne({_id: new mongodb.ObjectID(delete_id.toString())});
1000% works...
i think we have to require mongodb as const
and use it with mongodb
I recently stumbled with this problem today and I find that the fix is:
const mongodb = require('mongodb');
const ObjectID = require('mongodb').ObjectID;
databaseName.collectionName.deleteOne({_id: new mongodb.ObjectID(id)} , (err)=>{
if (err) throw err;
console.log('Deleted'+id);
});

TypeError: db.collection is not a function with user password restriction

I have a university project where I can ssh to a server that has a mongodb with fixed database/username/password. I imported a collection and now want to read it out with nodejs for testing. After starting it with node server.js it returns "Connected correctly to server" into console but then I get a TypeError: db.collection is not a function
What is wrong? Thanks
var MongoClient = require('mongodb').MongoClient;
const user = encodeURIComponent('x');
const password = encodeURIComponent('y');
const authMechanism = 'DEFAULT';
// Connection URL
const url = `mongodb://${user}:${password}#localhost:27017/database?authMechanism=${authMechanism}`;
MongoClient.connect(url, function(err, db) {
console.log("Connected correctly to server");//works
var cursor = db.collection('locations').find();//throws error
cursor.each(function(err, doc) {
console.log(doc);
});
});
Try this way:
var MongoClient = require('mongodb').MongoClient;
const user = encodeURIComponent('x');
const password = encodeURIComponent('y');
const authMechanism = 'DEFAULT';
// Connection URL
const url = `mongodb://${user}:${password}#localhost:27017/database?authMechanism=${authMechanism}`;
MongoClient.connect(url, function(err, db) {
if(err){
console.log("Connection failed");
}
else{
console.log("Connected correctly to server");
var cursor = db.collection('locations');//same error
cursor.find({}).toArray(function(err,docs){
if(err){
console.log("did'nt find any!")
}
else{
console.log(docs)
}
});
}
});
Got it working after all:
var MongoClient = require('mongodb').MongoClient;
const user = encodeURIComponent('x');
const password = encodeURIComponent('y');
const authMechanism = 'DEFAULT';
// Connection URL with and without authentication
const url = `mongodb://${user}:${password}#localhost:27017/database?authMechanism=${authMechanism}`;
//const url = `mongodb://localhost:27017/`;
MongoClient.connect(url, (err, db) => {
if(err) throw err;
console.log("connect works");
let database = db.db('database');
database.collection('users').find().toArray((err, results) => {
if(err) throw err;
results.forEach((value)=>{
console.log(value);
});
})
});

Updating an object attribute from a method

I'm trying to understand why the following code doesn't work. Basically, I want to handle the database connection in a Node module, while using the same database connection.
Here's my module:
var MongoClient = require("mongodb").MongoClient;
var url = "mongodb://localhost:27017";
module.exports = {
resource: null,
connect: function() {
MongoClient.connect(
url,
function(err, db) {
if (err) throw err;
console.log("Connected!");
this.resource = db; // Updating the object's attribute
}
);
},
};
And my main file:
var db = require('./db.js');
db.connect(); // Outputs "connected!"
http.createServer(function (req, res) {
console.log(db.resource) // Outputs "null"
}).listen(8080);
The resource attribute is never updated. I suspect a scope issue but I don't know how to address it.
The use of function() to define both exports.connect and the callback to MongoClient.connect causes the this ("context") binding on the function body to change to the function itself. To avoid this behaviour, use ES6' Arrow Function syntax, which does not change the context bindings:
var MongoClient = require("mongodb").MongoClient;
var url = "mongodb://localhost:27017";
module.exports = {
resource: null,
connect: () => {
MongoClient.connect(
url,
(err, db) => {
if (err) throw err;
console.log("Connected!");
this.resource = db; // Updating the object's attribute
}
);
},
};
Or you may move the connect definition outside of the object, and assign exports.resource through the use of a full object path, as so:
var MongoClient = require("mongodb").MongoClient;
var url = "mongodb://localhost:27017";
module.exports = {
resource: null,
connect: undefined
},
};
module.exports.connect = function() {
MongoClient.connect(
url,
function(err, db) {
if (err) throw err;
console.log("Connected!");
module.exports.resource = db; // Updating the object's attribute
}
);
};

How to get all the documents from mongodb?

How can I get all the documents from mongodb using nodejs SDK ? I tried following approach to get all the documents but could't get any however insertions is working fine.
// Connection URL
var url = config.mongodbConnectionString;
var db: any;
// Use connect method to connect to the Server
MongoClient.connect(url, function (err: any, database: any) {
assert.equal(null, err);
console.log("Connected correctly to server");
db = database;
});
export class MongodbProvider implements IDbProvider {
public getMenus(): any {
var menus: any = [];
try {
db.open(function (err, db) {
var cursor = db.collection('menus').find(function (err, cursor) {
cursor.each(function (err, doc) {
console.log(doc);
menus.push(doc);
});
});
});
}
catch (err) {
console.log(err);
}
return menus;
}
}
Can you please help me in this?
First parameter of find is a filter. To fetch everything, it should be an empty document. Something like:
var cursor = db.collection('menus').find({}, function (err, cursor) {

nodejs mongodb not deleteing based on id

Can you please help me with this code. This code is not deleting the value from MongoDB, while I am running this url : http://localhost:3000/delete/57c6713455a6b92e105c5250.
I am getting this response: {"lastErrorObject":{"n":0},"value":null,"ok":1}, but not deleting .
app.get('/delete/:id', (req, res) => {
var uid = req.params.id;
db.collection('quotes').findOneAndDelete({'_id': uid}, (err, result) => {
if (err) return res.send(500, err);
res.send(result);
});
});
In MongoDB you query a document id(_id) by using the ObjectId constructor and not the ObjectId's string. Thus the query needs to be: { '_id': ObjectId(uid) }.
Example
var mongoClient = require('mongodb').MongoClient;
//Include ObjectId
var ObjectId = require('mongodb').ObjectID;
mongoClient.connect("Your connection string", function(err, db) {
var query = {
_id: ObjectId("id_string") // Important to notice
};
var collection = db.collection('your collection');
collection.find(query, function(err, docs) {
console.log(err, docs);
});
});
Suggestion
//Include ObjectId
var ObjectId = require('mongodb').ObjectID;
app.get('/delete/:id', (req, res) => {
var uid = req.params.id;
//Add object id to query object
db.collection('quotes').findOneAndDelete({'_id': ObjectId(uid)}, (err, result) => {
if (err) return res.send(500, err);
res.send(result);
});
});
Yes. thank you i figured where i did wrong. see below correct answer.
var ObjectId = require('mongodb').ObjectID;
app.get('/delete/:id', (req, res) => {
var uid = req.params.id;
db.collection('quotes').findOneAndDelete({'_id': ObjectId(uid) }, (err, result) => {
if (err) return res.send(500, err);
res.send(result);
});
});
This response means, your query is executing properly "OK":1, but the find query is unable to find any doc to delete it.
So before using "findOneAndDelete" use only "findOne" and log the response to check weather you that doc or not.

Categories