I would like to upload a file from html form using an api written in node js.
Following code is the api to upload the file ,But i am not able to get the exact query for saving a file as attachment in the db.
server.post('/upload/', passport.authenticate('oauth-bearer', {
session: false
}), (req, res, next) => {
if(!req.body.userId || !req.body._id ) {
return res.send({"message":"missingParameter","statuscode":"404"});
}
else {
// // Retrieve
var MongoClient = require('mongodb').MongoClient;
// Connect to the db
MongoClient.connect("mongodb://localhost:27017/", function(err,client) {
var ObjectId = require('mongodb').ObjectId;
if (err) throw err;
var dbo = client.db("Db");
}
}
}
//below is the query to insert data .How to insert a file using mongodb query into cosmos db.
var data = { "_id" : ObjectId(req.body._id) ,"file":req.body.files};
dbo.collection("uploads").insert(data, function(err, result) {
if (err) throw err;
console.log("1 document inserted");
client.close();
return res.send({"message":"success"});
});
//
});
}
});
Related
I have uploaded data to MongoDB by pymongo and I want to retrieve it in my nodeJs. I am writing function like this but it is not working. my collection name is linux_trace and my database name is Linux_Trace_db.
The error is linux_trace is not defined
const mongoose = require("mongoose")
require('dotenv').config();
const URI = process.env.MONGO_URL;
mongoose.connect(
URI,
(err) => {
if (err) throw err;
console.log('Connected to mongodb');
}
);
linux_trace.find(function (err, adminLogins) {
if (err) return console.error(err);
console.log(adminLogins)})
The issue with your code is that you didn't define linux_trace as a variable in javascript.
To get access to a model in a mongo database that already has a collection, you can run something like this
const query = function (err, adminLogins) {
if (err) return console.error(err);
console.log(adminLogins)};
mongoose.connection.db.collection('linux_trace', function (err, collection) {
collection.find(query).toArray(cb);
});
I got this from this answer: https://stackoverflow.com/a/6721306/3173748
In the code I am trying to find all documents with code UE19CS204.But in the console.log
a big message is printed not the JSON data.The findOne() is working but not find().
I don’t know what change to do to find all documents with code UE19CS204.
var MongoClient = require(‘mongodb’).MongoClient;
var url = “mongodb://localhost:27017/”;
MongoClient.connect(url, { useUnifiedTopology: true } ,function(err, db) {
if (err) throw err;
var dbo = db.db(“pes”);
dbo.collection(“course”).find({“code”:“UE19CS204”}, function(err, result) {
if (err) throw err;
console.log(result);
});
dbo.collection(“course”).findOne({code:“UE19CS204”}, function(err, result) {
if (err) throw err;
console.log(result);
db.close();
});
});
The method find() creates a cursor for a query that can be used to iterate over results from MongoDB, see here.
Use toArray(), you can finde the documentation here.
dbo.collection(“course”).find({“code”:“UE19CS204”}).toArray(function(err, docs) {
if (err) {
throw err;
}
console.log(docs);
})
Full example:
const MongoClient = require('mongodb').MongoClient;
// Connection URL
const url = 'mongodb://localhost:27017';
// Database Name
const dbName = 'pes';
// Collection Name
const collectionName = 'course';
// Filter
const filter = { 'code': 'UE19CS204' }
// Use connect method to connect to the server
MongoClient.connect(url, { useUnifiedTopology: true }, function(err, client) {
if (err) {
throw err;
}
client.db(dbName).collection(collectionName).find(filter).toArray(function(err, docs) {
if (err) {
throw err;
}
console.log(docs);
})
client.close();
});
I need to update the data from client side in mongodb but I can see clicked updated Id value in node js but it does not update in mongodb wat to do.. help me to update the values in mongo db using id values
router.post('/datapassfup', (req, res) => {
console.log("updated values are",req.body)
MongoClient.connect(url, function(err, db) {
if (err) throw err;
var dbo = db.db("mohan");
var myquery = { id: req.body.id };
var newvalues = { $set: {name: req.body.name, username:
req.body.username } };
dbo.collection("customers").updateMany(myquery,newvalues,
function(err, res) {
if (err) throw err;
console.log("1 document updated");
db.close();
});
});
});
if you use the mongodb id for you query then you need to create a new objectid for _id search
const {ObjectId} = require("mongodb");
const query = {_id:new ObjectId(req.body.id)}
Using a MEAN Stack deployment on Heroku I am able to GET and DELETE Documents with mongoDB's findOne and deleteOne functions. However when I try to PUT a document with the mongoDB updateOne/update function, I receive this error (server side) :
The _id field cannot be changed from {_id: ObjectId('56d4d71191fdc81100974d0b')} to {_id: "56d4d71191fdc81100974d0b"}.
Seems strange because I am using the same method in my server code for updateOne as in findOne (again, findOne works fine):
app.get("/contacts/:id", function(req, res) {
db.collection(CONTACTS_COLLECTION).findOne({ _id: new ObjectID(req.params.id) }, function(err, doc) {
if (err) {
handleError(err.message, "Failed to get contact");
} else {
res.status(200).json(doc);
}
});
});
app.put("/contacts/:id", function(req, res) {
var updateDoc = req.body;
db.collection(CONTACTS_COLLECTION).updateOne({_id: new ObjectID(req.params.id)}, updateDoc, function(err, doc) {
if (err) {
handleError(err.message, "Failed to update contact");
} else {
res.status(204).end();
}
});
});
Any suggestions?
I think you have problem at var updateDoc = req.body
As req.body contains id field and you are searching from object to update by that id, mongodb thinks you are trying to update
id field too which is not allowed.
One solution is to remove id field from your updateDoc object.
e.g.
delete updateDoc._id;
now try again and see if it works.
Your final function should look like
app.put("/contacts/:id", function(req, res) {
var updateDoc = req.body;
delete updateDoc.id;
db.collection(CONTACTS_COLLECTION).updateOne({_id: new ObjectID(req.params.id)}, updateDoc, function(err, doc) {
if (err) {
handleError(err.message, "Failed to update contact");
} else {
res.status(204).end();
}
});
});
I am trying to connect to MongoDB with user/password , this is what I did so far:
var MongoClient = require('mongodb').MongoClient;
// Connect to the db
MongoClient.connect("mongodb://${host}:27017/${db}", function(err, db) {
if(!err) {
console.log("successfully connected to the database");
}else{
console.log("Error on connecting... aborting and exiting");
return console.dir(err);
throw err;
}
db.authenticate('username', 'password', function(err, res) {
console.log("reached here");
});
});
Now I am trying to login inside the data base in order to be able to get inside Mongo Database's collections, how can I do that?
Thanks!
You can perform CURD operations like following:
var MongoClient = require('mongodb').MongoClient;
// Connect to the db
MongoClient.connect("mongodb://${host}:27017/${db}", function(err, db) {
if(!err) {
console.log("successfully connected to the database");
//here you can perform operation
var collection = db.collection('test');
var doc1 = {'hello':'doc1'};
var doc2 = {'hello':'doc2'};
collection.insert(doc1);
}else{
console.log("Error on connecting... aborting and exiting");
return console.dir(err);
throw err;
}
db.authenticate('username', 'password', function(err, res) {
console.log("reached here");
});
});