I am trying to delete the entry from MOngoDb by using MEAN STACK with ANgular 4.(New to this technology)
typescript:
deleteitem(id){
let deleteresult;
let itemid = id;
this.dataService.deleteitem(itemid)
.subscribe(res =>deleteresult =res,
err => this.apiError = err,
)
};
dataservice:
deleteitem(itemid): Observable<any>{
let data =new URLSearchParams();
data.set('deleteId', itemid);
console.log(data.toString());
return this.http.post(URL, data.toString())
.map(res=> res.json())
.catch((error:any) => Observable.throw('Server Error To delete the item'));
}
Router.js
const ObjectID = require('mongodb').ObjectID;
router.post('/deleteitem', function(req, res){
MongoClient.connect('URL',function(err, client){
if (err) throw err;
var myDB = client.db('DbName');
var collection = myDB.collection('collectionName');
console.log(req.body);
//var objectId = collection.getObjectId();
collection.remove({_id: ObjectId(req.body.deleteId), function(err, result)
{
res.send((result==1)?{msg:deleted} : {msg:"error:"+ err});
}});
})
})
Error:
ObjectId is not defined.
Also the console.log(req.body) gives a "{}" value. Not sure why.
But console.log(data.toString()); in the dataservice gives the value of intended _id to be removed from MongoDb.
Try using data instead of data.toString() in
return this.http.post(URL, data.toString())
This will give you output value in console.log(req.body);
Also, try replacing the below line of code
collection.remove({_id: ObjectId(req.body.deleteId), function(err, result)
with
collection.deleteOne({_id: new mongodb.ObjectID(req.body.deleteId)}, function(err, result)
You need to create a new instance of mongodb here.
Hope this works.
Related
Below is the code which i used to up the server. It is running in the localhost server 3000.
app.use('/', books);
app.listen(3000, function(){
console.log('Server running at port 3000: http://localhost:3000')
});
Below code throws mongodb error. Dont know what exactly the error. Below is my code
var express = require('express');
var router = express.Router();
var MongoClient = require('mongodb').MongoClient;
var url = 'mongodb://127.0.0.1:27017';
// SHOW LIST OF BOOKS
router.get('/book', function(req, res, next) {
MongoClient.connect(url, function(error, db) {
if (error) throw error;
var dbo = db.db("BookStore");
dbo.collection("Books").find().toArray(function(err, result) {
if (err) throw err;
res.send(result);
console.log(result);
db.close();
});
});
});
// SHOW BOOK with ISBN
router.get('/book/:isbn', function(req, res, next) {
var isbn = parseInt(req.params.isbn);
MongoClient.connect(url, function(error, db) {
if (error) throw error;
var dbo = db.db("BookStore");
var query = { "isbn": isbn };
dbo.collection("Books").findOne(query, function(err, result) {
if (err) throw err;
res.send(result);
console.log(result);
db.close();
});
});
});
// Add BOOK
router.post('/book', function(req, res, next) {
MongoClient.connect(url, function(error, db) {
if (error) throw error;
var dbo = db.db("BookStore");
var myobj = {
"isbn":req.body.isbn,
"publisher":req.body.publisher,
"title":req.body.title,
"authors":req.body.authors,
"publishedDate":req.body.publishedDate,
"price":req.body.price
};
dbo.collection("Books").insertOne(myobj, function(err, result) {
if (err) throw err;
res.send('Book with '+req.body.isbn+' is successfully added');
db.close();
});
});
});
// UPDATE BOOK
router.put('/book/:isbn', function(req, res, next) {
var isbn = parseInt(req.params.isbn);
MongoClient.connect(url, function(error, db) {
if (error) throw error;
var dbo = db.db("BookStore");
var query = { "isbn": isbn };
var newvalues = { $set: {
"publisher":req.body.publisher,
"title":req.body.title,
"authors":req.body.authors,
"publishedDate":req.body.publishedDate,
"price":req.body.price
}
};
dbo.collection("Books").updateOne(query, newvalues, function(err, result) {
if (err) throw err;
res.send('Book with '+req.params.isbn+' is successfully updated');
db.close();
});
});
});
// DELETE BOOK
router.delete('/book/:isbn', function(req, res, next) {
var isbn = parseInt(req.params.isbn);
MongoClient.connect(url, function(error, db) {
if (error) throw error;
var dbo = db.db("BookStore");
var query = { "isbn": isbn };
dbo.collection("Books").deleteMany(query, function(err, result) {
if (err) throw err;
res.send('Book with '+req.params.isbn+' is successfully removed');
db.close();
});
});
});
module.exports = router;
Code Explanation:
We are creating a route to our application called 'Books.' So
whenever anybody browses to http://localhost:3000/books of our application, the code snippet defined for this route will be
executed.
Here we are getting all of the records in our 'Books'
collection through the db.collection('Books').find() command. We are then assigning this collection to a variable called cursor. Using this cursor variable, we will be able to browse through all of the records of the collection.
Run sudo mongod in the terminal
Is it impossible to connect even if you change the value assigned to the variable url to mongodb://[user_name]:[password]#127.0.0.1:27017/[your_database_name]?authSource=admin ?
Actually, the error is related to MongoDB version(MongoClient.connect(url, function(error, db)), MongoDB developers have changed their API. I don't know which version, it throws an error when you use MongoClient.connect(url, function(error, db).
So it should be MongoClient.connect(url, function(err, client)
Link to api-doc
And do not forget to run mongod
i'm having an issue querying my mongodb database. i'm using react js. the problem doesn't seem to be the connection because i can save to the database just fine, i can only assume its a syntax issue. i've looked around but couldn't find a fix. below is a snippet of code from the schema.js file and the index.js file:
Schema.js
//import dependency
var mongoose = require('mongoose')
var Schema = mongoose.Schema
//create new instance of the mongoose.schema. the schema takes an
//object that shows the shape of your database entries.
var UserSchema = new Schema({
socketId: String
})
//export our module to use in server.js
module.exports = mongoose.model('User', UserSchema)
index.js
var mongoose = require('mongoose')
var db = mongoose.connect('mongodb://mongodatabase', {
useMongoClient: true,
/* other options */
})
var UserSchema = require('../schema/Schemas');
function userExist(userList, username){
var usert = new UserSchema()
var query = usert.where({socketId: username})
query.findOne(function (err, usert) {
if (err) return handleError(err);
if (usert) {
// doc may be null if no document matched
}
});
return username in userList
// return query
}
I get the error : usert.where is not a function.
i tried using just find but i get the same error
any help would be welcome, Thank you
You should use .findOne function directly on your schema class instead of .where
Like this :
UserSchema.findOne({socketId: username}, function (err, usert) {
if (err) return handleError(err);
if (usert) {
// doc may be null if no document matched
}
});
.where must be used on query, not schema.
To use .where, you can do it like this :
User.findOne().where({ socketId: username }).exec( function (err, usert) {
if (err) return handleError(err);
if (usert) {
// doc may be null if no document matched
}
})
I'm trying to read some data from a mongodb database with graphql and mongoose but everytime I query the db it returns null but no error is thrown.
Here's the code:
// Controller.js
exports.user_read = function(id) {
return new Promise((resolve, reject) => {
Contact.findById(id, function(err, user) {
err ? reject(err) : resolve(user);
}
});
}
// Resolver.js
var contact = require('Controller');
...
// root object passed as rootValue to graphqlHTTP
getUser: ({ id }) => {
contact.user_read(id)
}
...
Any tips and help would be appreciated.
P.S. This also seems to be happening with all my queries which take the same Promise format in the controller.js file.
You need to await contact.user_read(id). Without the await, you are simply sending back a Promise. It's most likely pending when it is returned, therefore the null return.
Including Daniel Rearden's suggestion to get rid of the extra Promise, here's what your code would look like:
// Controller.js
exports.user_read = async id => {
return Contact.findById(id, (err, user) => {
err ? reject(err) : resolve(user);
});
}
// Resolver.js
var contact = require('Controller');
...
// root object passed as rootValue to graphqlHTTP
getUser: ({ id }) => {
return await contact.user_read(id)
}
...
From homework 2_2 of the M101JS course at university.mongodb.com.
Write a program that finds the document with the highest recorded temperature for each state, and adds a "month_high" field for that document, setting its value to true.
The following code should work to update the correct doc in the collection adding "month_high". And the problem is here:
//db.collection('data').update(query, setMonthHigh, function(err, updated) {//OK
db.collection('data').update(query, doc, function(err, updated) {// NOT OK, dunno why
The 2nd update line does not save anything. But if I use the commented update above, it works.
Does anyone have an idea why the 2nd update line isn't working (the one that replaces the whole doc)?
var MongoClient = require('mongodb').MongoClient;
MongoClient.connect('mongodb://localhost:27017/weather', function(err, db) {
if(err) throw err;
var options = { 'sort' : [ ['State', 1], ['Temperature', -1] ]};
var lastDoc = null;
var setMonthHigh = {'$set':{'month_high':true}};
var cur = db.collection('data').find({}, {},options);
//var cur = db.collection('data').find({'month_high':true}, {},options);
cur.each(function(err, doc) {
if(err) throw err;
if(doc == null) {
console.log("Document done");
//return db.close();
db.close();
process.exit(0);
}
var query = {'_id' : doc._id};
//db.collection('data').update({'month_high':true}, {$unset:{'month_high':1}}, function(err, updated) {});
//console.dir(doc);
if ( ( lastDoc != null && lastDoc.State != doc.State ) ||
lastDoc == null )
{
doc['month_high'] = 'true';
//db.collection('data').update(query, setMonthHigh, function(err, updated) {//OK
db.collection('data').update(query, doc, function(err, updated) {
// NOT OK, dunno why
if(err) throw err;
console.dir("Update "+updated);
});
console.dir(doc);
}
lastDoc = doc;
});
});
Also, I'm told that using process.exit(0) is a bad hack, but it was the only way I could exit the code without throwing exceptions on return db.close();. If anyone knows a way to exit the code gracefully, that would be great too.
First of all, you have made a mistake in part of your code responsible for updating a database.
db.collection('data').update is an asynchronous function. It means that you cannot execute db.close() without knowing if all updates have been completed. For more details please read: How can I use a cursor.forEach() in MongoDB using Node.js?
Both updates works. However there is one difference between two of them:
db.collection('data').update(query, setMonthHigh, function(err, updated)
updates records with a new field: 'month_high': true <- boolean value
Query to find these records is: db.data.find({'month_high': true})
db.collection('data').update(query, doc, function(err, updated)
updates records with a new field: 'month_high': 'true' <- string value
Query to find these records is: db.data.find({'month_high': 'true'})
Your updated code:
Before run it, first install async library (npm install async)
var async = require('async');
var MongoClient = require('mongodb').MongoClient;
MongoClient.connect('mongodb://localhost:27017/weather', function(err, db) {
if(err) throw err;
var q = async.queue(function (doc, callback) {
db.collection('data').update({_id: doc._id}, doc, callback);
}, Infinity);
var options = { 'sort' : [ ['State', 1], ['Temperature', -1] ]};
var lastDoc = null;
var cur = db.collection('data').find({}, {},options);
cur.each(function(err, doc) {
if(err) throw err;
if(doc === null) return;
if ( ( lastDoc !== null && lastDoc.State !== doc.State ) ||
lastDoc === null )
{
doc['month_high'] = true;
q.push(doc, function(err, updated) {
if(err) throw err;
console.log("Update "+updated);
});
}
lastDoc = doc;
});
q.drain = function() {
if (cur.isClosed()) {
console.log('Document done');
db.close();
}
}
});
//router
app.get('/retrieve_report', function(req, res) {
var retrieved = retrieve_report(req, res);
res.render('retrieve_report.ejs', {
'report' : retrieved
});
});
//Load up the report model
var Report = require('../models/report');
console.log('Report ' + Report.schema);
//expose this function to our app using module.exports
//query
module.exports = function(req, res) {
//console.log('param ' + res.send);
var query = Report.findById(req.param('id'), function(err, doc) {
if(err) {
throw err;
}
else {
console.log('doc ' + JSON.stringify(doc));
res.send(doc);
}
});
}
//app.js
var retrieve_report = require('./config/retrieve_report');//which is the above code
I want to return the document to the router so that I can put its information into my view. I tried "res.json(doc), but that gave me the error, "throw new Error('Can\'t set headers after they are sent.');" Everyone says to use a callback function, but aren't I using a callback function here?
As your error says:
but that gave me the error, "throw new Error('Can\'t set headers after they are sent.');"
Means you are trying to send data the twice.
Sample code:
app.get('/retrieve_report', function(req, res) {
var query = Report.findById(req.param('id'), function(err, doc) {
if(err) {
throw err;
}
else {
console.log('doc ' + JSON.stringify(doc));
res.send(doc);
}
});
This should work..