Document is not deleting in MongoDB - javascript

I am using NodeJs and MongoDB as a backend service.I am trying to delete document on MongoDB but couldn't delete but sending response deleted.
This what I have done so far:
const express = require('express');
const MongoClient = require('mongodb').MongoClient;
const app = express();
var dburl = process.env.URL;
app.post('/deleteRow', (req,res) => {
MongoClient.connect(dburl,{useNewUrlParser:true}, (err,client) => {
var myquery = { _id:req.body.postId};
if(err){
console.log("Error:", +err);
}
else{
var collect = client.db('abc').collection('xyz');
collect.deleteOne(myquery, function(err,obj){
if(err){
console.log("Error".red, +err);
}
else{
res.send("Deleted");
}
});
}
});
});
Let me know what I need to correct in above code. Any help would be appreciated.
THANKS

Try casting your req.body.postId to an ObjectId
Something like
var ObjectID = require(‘mongodb’).ObjectID;
var postId = new ObjectID(req.body.postId);
Then use that postId in your deleteOne({}) params

Related

What does mongodb is not a function mean?

I'm new to programming, I'm trying to follow a web developemnt course when connecting to database I created I get the error "mongodb.connect is not a function".
I try to connect to the database using the following code.
let mongodb = require('mongodb');
let db
let connectionString = '';
mongodb.connect(connectionString,{useNewUrlParser: true, useUnifiedTopology:
true},function(err, client){
db = client.db();
You can connect to the database from the client (which uses MongoClient from the library).
const { MongoClient } = require('mongodb');
let db;
const connectionString = 'mongodb://' // Change this to your uri
const client = new MongoClient(connectionString)
Then you can connect
await client.connect();
db = client.db();
Try this:
const { MongoClient } = require("mongodb");
let databaseName = '';
let connectionString = '';
MongoClient.connect(connectionString, {useNewUrlParser: true, useUnifiedTopology: true}, (error, client) => {
if (error)
return console.log("Connection failed for some reason");
const db = client.db(databaseName);
});
just try this one
let mongodb = require('mongodb').MongoClient;
this could be for the version of mongodb you are using instead of version used in the course.

Using objectid can't retrieve data from MongoDB in Node.js

When I pass objectid of 1 hospital from Postman to this program it returns only empty array. But there is one data matching that objectid. Can you help me solve this? When I try to debug the program in console, I saw the array is empty.
doctor.js:
var express = require('express');
var router = express.Router();
var app=express()
var bodyParser = require("body-parser");
var validator = require('validator');
var mongo= require('./mongoconnect')
var authentication=require('./check_authentication')
var validate = require('./validation')
var ObjectId=require('mongodb').ObjectId
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
router.post('/',function(req,res)
{
if(validate.name(req.body.name) && validate.length(req.body.name) && validate.empty(req.body.name))
{
if(validate.empty(req.body.hospital_id))
{
mongo.find("hospital","_id",ObjectId(req.body.hospital_id),function(result1)
{
if(result1.length==1)
{
res.send("succcess")
}
})
}
}
})
module.exports = router;
And collection of MongoDB is:
hospital:
{
"_id" : ObjectId("5aa92df0ec6b3cc78ff88afd"),
"name" : "apollo_hospitals"
}
{
"_id" : ObjectId("5aa92df9ec6b3cc78ff88afe"),
"name" : "fortis"
}
mongoconnect.js:
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/";
var dbo=null;
exports.connection=function()
{
if(dbo!=null) return
MongoClient.connect(url, function(err, db)
{
if (err) throw err;
dbo = db.db("hospital_api");
});
}
var get = function (){
return dbo;
}
exports.find=function(collections,key,value,callback)
{
get().collection(collections).find({key:value}).toArray(function(err,result)
{
// console.log(collections)
// console.log(key)
// console.log(value)
if(err) throw err;
console.log(result)
callback(result)
})
}
Here, myself i got the solution.
We have to declare ObjectID with New keyword..
Var some_variable = New ObjectID(_id)
After that we can use that id anywhere using that some_variable

objectId.isValid is not a function in making API requests

I am trying to make individual API get requests in server.js but I don't get the desired results. The error that I get in Postman is as followed:
objectId.isValid is not a function in making API request
Here is the code of server.js:
var express=require('express');
var bodyParser=require('body-parser');
var ObjectID = require('mongodb');
var mongoose=require('./db/mongoose');
var Todo=require('./models/todo');
var User=require('./models/user');
var app = express();
app.get('/todos/:id', (req, res) => {
var id=req.params.id;
if (!ObjectID.isValid(id)) {
return res.status(404).send();
}
Todo.findById(id).then((todo) => {
if (!todo) {
return res.status(404).send();
}
res.send({todo});
}).catch((e) => {
res.status(400).send();
});
});
Note: This is answered in the comments. Writing a detailed answer to help completeness of this post.
ObjectID is a property of the object returned by require('mongodb'), which is why var ObjectID = require('mongodb').ObjectID works fine.
If you switch to ES6, object destructuring assignment comes handy.
const { ObjectID } = require('mongodb');
http://mongodb.github.io/node-mongodb-native/3.0/api/ObjectID.html
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment

How to use another MongoDB database using Node.js [duplicate]

How do I connect to mongodb with node.js?
I have the node-mongodb-native driver.
There's apparently 0 documentation.
Is it something like this?
var mongo = require('mongodb/lib/mongodb');
var Db= new mongo.Db( dbname, new mongo.Server( 'mongolab.com', 27017, {}), {});
Where do I put the username and the password?
Also how do I insert something?
Thanks.
Per the source:
After connecting:
Db.authenticate(user, password, function(err, res) {
// callback
});
Everyone should use this source link:
http://mongodb.github.com/node-mongodb-native/contents.html
Answer to the question:
var Db = require('mongodb').Db,
MongoClient = require('mongodb').MongoClient,
Server = require('mongodb').Server,
ReplSetServers = require('mongodb').ReplSetServers,
ObjectID = require('mongodb').ObjectID,
Binary = require('mongodb').Binary,
GridStore = require('mongodb').GridStore,
Code = require('mongodb').Code,
BSON = require('mongodb').pure().BSON,
assert = require('assert');
var db = new Db('integration_tests', new Server("127.0.0.1", 27017,
{auto_reconnect: false, poolSize: 4}), {w:0, native_parser: false});
// Establish connection to db
db.open(function(err, db) {
assert.equal(null, err);
// Add a user to the database
db.addUser('user', 'name', function(err, result) {
assert.equal(null, err);
// Authenticate
db.authenticate('user', 'name', function(err, result) {
assert.equal(true, result);
db.close();
});
});
});
var mongo = require('mongodb');
var MongoClient = mongo.MongoClient;
MongoClient.connect('mongodb://'+DATABASEUSERNAME+':'+DATABASEPASSWORD+'#'+DATABASEHOST+':'DATABASEPORT+'/'+DATABASENAME,function(err, db){
if(err)
console.log(err);
else
{
console.log('Mongo Conn....');
}
});
//for local server
//in local server DBPASSWOAD and DBusername not required
MongoClient.connect('mongodb://'+DATABASEHOST+':'+DATABASEPORT+'/'+DATABASENAME,function(err, db){
if(err)
console.log(err);
else
{
console.log('Mongo Conn....');
}
});
I find using a Mongo url handy. I store the URL in an environment variable and use that to configure servers whilst the development version uses a default url with no password.
The URL has the form:
export MONGODB_DATABASE_URL=mongodb://USERNAME:PASSWORD#DBHOST:DBPORT/DBNAME
Code to connect this way:
var DATABASE_URL = process.env.MONGODB_DATABASE_URL || mongodb.DEFAULT_URL;
mongo_connect(DATABASE_URL, mongodb_server_options,
function(err, db) {
if(db && !err) {
console.log("connected to mongodb" + " " + lobby_db);
}
else if(err) {
console.log("NOT connected to mongodb " + err + " " + lobby_db);
}
});
My version:
var MongoClient = require('mongodb').MongoClient;
MongoClient.connect('mongodb://user:pass#dhost:port/baseName', function(err, db) {
if (err) {
console.error(err);
}
var collection = db.collection('collectionName');
collection.find().toArray(function(err, docs) {
console.log(docs);
});
});
I recommend mongoskin I just created.
var mongo = require('mongoskin');
var db = mongo.db('admin:pass#localhost/mydb?auto_reconnnect');
db.collection('mycollection').find().toArray(function(err, items){
// do something with items
});
Is mongoskin sync? Nop, it is async.
Here is new may to authenticate from "admin" and then switch to your desired DB for further operations:
var MongoClient = require('mongodb').MongoClient;
var Db = require('mongodb').Db, Server = require('mongodb').Server ,
assert = require('assert');
var user = 'user';
var password = 'password';
MongoClient.connect('mongodb://'+user+':'+password+'#localhost:27017/opsdb',{native_parser:true, authSource:'admin'}, function(err,db){
if(err){
console.log("Auth Failed");
return;
}
console.log("Connected");
db.collection("cols").find({loc:{ $eq: null } }, function(err, docs) {
docs.each(function(err, doc) {
if(doc) {
console.log(doc['_id']);
}
});
});
db.close();
});
This worked for me:
Db.admin().authenticate(user, password, function() {} );
You can do it like this
var db = require('mongo-lite').connect('mongodb://localhost/test')
more details ...
if you continue to have problems with the native driver, you can also check out sleepy mongoose. It's a python REST server that you can simply access with node request to get to your Mongo instance.
http://www.snailinaturtleneck.com/blog/2010/02/22/sleepy-mongoose-a-mongodb-rest-interface/
With the link provided by #mattdlockyer as reference, this worked for me:
var mongo = require('mongodb');
var server = new mongo.Server(host, port, options);
db = new mongo.Db(mydb, server, {fsync:true});
db.open(function(err, db) {
if(!err) {
console.log("Connected to database");
db.authenticate(user, password, function(err, res) {
if(!err) {
console.log("Authenticated");
} else {
console.log("Error in authentication.");
console.log(err);
}
});
} else {
console.log("Error in open().");
console.log(err);
};
});
exports.testMongo = function(req, res){
db.collection( mycollection, function(err, collection) {
collection.find().toArray(function(err, items) {
res.send(items);
});
});
};
Slight typo with Chris' answer.
Db.authenticate(user, password, function({ // callback }));
should be
Db.authenticate(user, password, function(){ // callback } );
Also depending on your mongodb configuration, you may need to connect to admin and auth there first before going to a different database. This will be the case if you don't add a user to the database you're trying to access. Then you can auth via admin and then switch db and then read or write at will.
const { MongoClient } = require('mongodb');
// or as an es module:
// import { MongoClient } from 'mongodb'
// Connection URL
const url = 'mongodb://localhost:27017';
const client = new MongoClient(url);
// Database Name
const dbName = 'myProject';
async function main() {
// Use connect method to connect to the server
await client.connect();
console.log('Connected successfully to server');
const db = client.db(dbName);
const collection = db.collection('documents');
// the following code examples can be pasted here...
return 'done.';
}
main()
//what to do next
.then(console.log)
//if there is an error
.catch(console.error)
// what to do in the end(function result won't matter here, it will execute always).
.finally(() => client.close());
you can find more in the documentation here: https://mongodb.github.io/node-mongodb-native/4.1/
I'm using Mongoose to connect to mongodb.
Install mongoose npm using following command
npm install mongoose
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/database_name', function(err){
if(err){
console.log('database not connected');
}
});
var Schema = mongoose.Schema;
var userschema = new Schema ({});
var user = mongoose.model('collection_name', userschema);
we can use the queries like this
user.find({},function(err,data){
if(err){
console.log(err);
}
console.log(data);
});

Can't canonicalize query: IndexNotFound: text index required for $text query', code: 17287

The error is triggered in the Product.find statement below:
var bodyparser = require('body-parser');
var express = require('express');
var status = require('http-status');
var _ = require('underscore');
var mongoose = require('mongoose');
var productSchema = require('./product');
var schema = new mongoose.Schema(productSchema);
schema.index({ name: 'text' });
module.exports = function(wagner) {
var api = express.Router();
api.use(bodyparser.json());
api.get('/product/text/:query', wagner.invoke(function(Product) {
return function(req, res) {
console.log("we are in the get " + req.params.query);
Product.
find(
{ $text : { $search : req.params.query } },
{ score : { $meta: 'textScore' } }).
sort({ score: { $meta : 'textScore' } }).
limit(10).
exec(handleMany.bind(null, 'products', res));
};
}));
return api;
};
function handleMany(property, res, error, result) {
console.log("We are handling the many");
if (error) {
console.log(error);
return res.
status(status.INTERNAL_SERVER_ERROR).
json({ error: error.toString() });
}
var json = {};
json[property] = result;
res.json(json);
}
I'm running MongoDB 3.4.2 on windows 10. I explicitly ran the statement db.products.ensureIndex({name: "text"}); in the MongoDB shell and for the first time I didn't get the error. It still gets timeout errors intermittently, though, when the query takes more than 2000 ms. I thought that I didn't have to explicitly add an index in the MongoDB shell because I'm putting on a schema index in the above code, but I don't know for sure.
Thanks,
William
I got into the MongoDB shell and put the index on the products collection like this:
db.products.createIndex({name: "text"})
That was my solution, and it worked, but I don't know if there was a glitch somewhere that made that solution necessary.

Categories

Resources