In mongodb i have a database schema like this :
_id : ObjectId('123456')
name: "abc"
number:"1"
i using this nodejs code so when enter the name i received the whole data above:
app.post("/showid", (req, res) => {
let name = req.body.name;
MongoClient.connect(uri, function (err, db) {
if (err) throw err;
var dbo = db.db("mydb");
dbo
.collection("mycollection")
.find({ name :name })
.toArray(function (err, result) {
if (err) throw err;
res.json(result);
db.close();
});});});
i still received an array of the data i want inside , but when i changed name to id ,
find({ _id: id })
and i enter the string inside ObjectId , i received an empty array . What did i do wrong ?
Related
When i Try to push key:value pair with the following code, it inserts data as object instead of key value pair. Following is the code im using to insert data into MongoDb
MongoClient.connect(url, function (err, db) {
if (err) throw err;
var dbo = db.db("Test");
var myquery = { userId: "test#gmail.com" };
// var newvalues = { $set: { name: "Mickey", address: "Canyon 123" } };
var newvalues = {
$push: { questionAnsId: { $each: [{ wk: 5 }] } }
}
dbo.collection("Forms").updateOne(myquery, newvalues, function (err, res) {
if (err) throw err;
console.log("1 document updated");
db.close();
});
});
Upon inserting data, this is what im getting
enter image description here
instead of saving data in
questionAnsId: {Object}
i want to save it as
questionAnsId:{key:value, key:value}
Any Idea how to solve this ?
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();
});
How can I delete particular data in mongodb using node.js ?
router.post('/deletedata', (req, res) => {
console.log("deleted values are",req.body.id)
MongoClient.connect(url, function(err, db) {
if (err) throw err;
var dbo = db.db("mohan");
var myquery = req.body.id;
console.log("myquery value is:", myquery)
dbo.collection("customers").remove({myquery}, function(err, obj) {
if (err) throw err;
db.close();
});
});
res.json({
statusCode: 200,
result: "success",
})
}
);
export default router;
I got particular id from React hooks crud app , So i can see the id in node js but it does not delete the that particular id data in mongoDB
Your query will only delete documents with myquery: passedId
I bet query should look like {_id: myquery}
dbo.collection("customers").remove({_id: myquery}, function(err, obj) {
if (err) throw err;
db.close();
});
dbo.collection("customers").remove(myquery, function(err, obj) {
if (err) throw err;
db.close();
});
try using delete({query}) or deleteMany({query})
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)}
I am not able to insert data into MongoDB database using insert method in Nodejs.
var url = 'mongodb://localhost:27017/learnyoumongo';
var mongo = require('mongodb').MongoClient;
mongo.connect(url, function(err, db) {
if (err) throw err;
// db gives access to the database
const myDb = db.db('learnyoumongo');
var docs = myDb.collection('docs');
var obj = {firstName: process.argv[2], lastName: process.argv[3]};
docs.insert(obj, function(err, res){
if(err) throw err;
console.log('data inserted');
})
db.close();
}
There is no output coming and connection to the data base is successful but no insertion of data is happening.
Try this will work for you .
var url = 'mongodb://localhost:27017/learnyoumongo';
var mongo = require('mongodb').MongoClient;
mongo.connect(url, function(err, dbobj) {
if (err) throw err;
// db gives access to the database
// const myDb = dbobj.db('learnyoumongo').collection('docs');
// var docs = myDb.collection('docs');
var obj = {firstName: process.argv[2], lastName: process.argv[3]};
dbobj.db('learnyoumongo').collection('docs').insert(obj, function(err, res){
if(err) throw err;
console.log('data inserted');
dbobj.close();
})
})
I figured out what the problem is. Seems like I forgot to add a parenthesis in the end:
var url = 'mongodb://localhost:27017/learnyoumongo';
var mongo = require('mongodb').MongoClient;
mongo.connect(url, function(err, db) {
if (err) throw err;
// db gives access to the database
const myDb = db.db('learnyoumongo');
var docs = myDb.collection('docs');
var obj = {firstName: process.argv[2], lastName: process.argv[3]};
docs.insert(obj, function(err, res){
if(err) throw err;
console.log('data inserted');
})
db.close();
})
You can use the following code to insert data into MongoDB using nodejs.
var mongo = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/learnyoumongo";
mongo.connect(url, function(err, db) {
if (err) throw err;
//access to the database
var myobj = { firstname: "Jhon", lastname: "Mackey" };
db.collection("docs").insertOne(myobj, function(err, res) {
if (err) throw err;
console.log("Data inserted");
db.close();
});
});