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
Related
so I am working with node.js and mongodb and I am a rookie
The below us my code:
const MongoClient = require('mongodb').MongoClient;
const url = 'mongodb://localhost:27017/myproject';
MongoClient.connect(url,function(err,db){
if (err){
return console.dir(err);
}
console.log('connected to mdb');
InsertDoc(db,function(){
db.close();
})
});
const InsertDoc= function(db, callback){
const collection = db.collection('users');
collection.insert({
name : 'vishnu',
email:'vishnu#123'
},
function(err,result){
if(err){
return console.dir(err);
}
console.log('inserted doc');
console.log(result);
callback(result);
});
}
ERROR: TypeError: db.collection is not a function
I am not sure where I have gone wrong
kindly let me know the mistake
The callback from connect will return you an instance of MongoClient and an instance of Db, as mentioned in official Mongodb Node driver documentation, look at the second example
https://mongodb.github.io/node-mongodb-native/4.1/classes/MongoClient.html
Once you obtain the collection you will have to get the db by using client.db(dbName) which will give you the db object for creating a collection.
// Connect using the MongoClient.connect static method
const MongoClient = require('mongodb').MongoClient;
// Connection url
const url = 'mongodb://localhost:27017/myproject';
// Connect using MongoClient
MongoClient.connect(url, function(err, client) {
const db = client.db("myproject");
const collection = db.collection("users");
// do your thing
client.close();
});
`
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 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"});
});
//
});
}
});
I have been trying to work with mongodb and to insert some data but I am getting an error .
Here is the code .
const MongoClient = require('mongodb').MongoClient;
MongoClient.connect('mongodb://localhost:27017/TodoApp', (err, db) => {
if (err) {
return console.log('Unable to connect to MongoDB server');
}
console.log('Connected to MongoDB server');
db.collection('Users').insertOne({
name: 'Andrew',
age: 25,
location: 'Philadelphia'
}, (err, result) => {
if (err) {
return console.log('Unable to insert user', err);
}
console.log(result.ops);
});
db.close();
});
The native driver for MongoDB has changed what its .connect() method provides to you in recent versions.
3.0
connectCallback(error, client)
2.2
connectCallback(error, db)
These being how your (err, db) => { ... } callback is defined in the documentation.
The .connect() method provides you a MongoClient instance. Including the database name in the connection address at least doesn't appear to change that.
You'll have to instead use the client's .db() method to get a Db instance with collections.
const dbName = 'TodoApp';
MongoClient.connect('mongodb://localhost:27017/', (err, client) => {
if (err) { ... }
let db = client.db(dbName);
db.collection('Users')...;
});
I don't need schema validation, so I'd rather not add the weight of Mongoose to my project. Unfortunately, I am unable to find a way in MongoClient; I'm unable to get my function outside of the mongo.connect ({}) scope, so that I can export my callback functions.
const mongo = require('mongodb').MongoClient;
const uri = "mongodb://localhost:27017";
mongo.connect(uri, function (err, db) {
const dbo = db.db("readings");
if (err) {
throw err;
};
console.log('MongoDB connected...')
function insertReading (data) {
dbo.collection("myReadings").insertOne(data, function(err, res) {
if (err) throw err;
console.log("1 document inserted");
});
};
});
exports.newReading = function(req, res) {
insertReading(req.body)
};
exports.myDashboard = function (req, res) {
console.log("test");
}
The "newReading" function would pertain to a POST verb and the "myDashboard" function to a GET verb. Putting my exports inside of the scopes of course will throw errors. How do I get my "insertReading" function to function for my out-of-scope function?