Say previously I had inserted a document into a mongo collection.
MongoClient.connect(url, function(err,db){
if(err) {throw err;}
else {
document = {action: "alert",
protocol: "udp",
port: "80",
_id: "12" }
var collection = db.collection("connections");
collection.insertOne(document, function(err,result){
if (err) {throw err;}
else {
console.log("Successful")
db.close();
}
}
}
Now I want to update the protocol field. What I have with no luck so far is
MongoClient.connect(url, function(err,db){
if (err) { throw err; }
else {
var collection = db.collection("connections");
collection.findOneAndUpdate({_id: "12"}, {$set: {protocol: "http"}}, {new: true}, function(err,doc) {
if (err) { throw err; }
else { console.log("Updated"); }
});
}
});
Am I passing the wrong parameters to the findOneAndUpdate method? I connect to the database correctly.
I think you should try
MongoClient.connect(url, function(err,db){
if (err) { throw err; }
else {
var collection = db.collection("connections");
collection.findOneAndUpdate({_id: "12"}, {$set: {protocol: "http"}}, {upsert: true}, function(err,doc) {
if (err) { throw err; }
else { console.log("Updated"); }
});
}
});
If "upsert" set to true, creates a new document when no document matches the query criteria.
=== Aug 2021
Here is an example of using findOneAndUpdate and getting back the updated document:
With the release of v4 of the node.js client, it seems the old solution of returnOriginal: false (which was awful anyway) is no longer the correct answer.
To see the list of available options for the node.js findOneAndUpdate method: https://mongodb.github.io/node-mongodb-native/4.0/interfaces/findoneandupdateoptions.html
But in short, this should work:
const doc = await <Collection>.findOneAndUpdate(
{ ... search },
{
$set: {
field1: 'value 1',
field2: ['value 2'],
etc.
},
},
{
upsert: true,
returnDocument: 'after', // this is new !
}
)
your third {new: true} argument is not valid
MongoClient.connect(url, function(err,db){
if (err) { throw err; }
else {
var collection = db.collection("connections");
collection.findOneAndUpdate({"_id": "12"}, {$set: {"protocol": "http"}}, function(err,doc) {
if (err) { throw err; }
else { console.log("Updated"); }
});
}
});
Here to update the record,it is not needed to use {upsert: true} and {new: true}. This solution works better.Try it once and suggest me if any errors in the code.
insert the update document if nothing matches the filter then use upsert.
MongoClient.connect(url, function(err,db){
if (err) { throw err; }
else {
var collection = db.collection("connections");
collection.findOneAndUpdate({_id: "12"}, {protocol: "http"}, {new: true}, function(err,doc) {
if (err) { throw err; }
else { console.log("Updated"); }
});
}
});
Related
const obj =[
{userName:'a',firstName:'kote',lastName:'perumalla '},
{userName:'a',firstName:'kote',lastName:'perumalla '},
{userName:'as',firstName:'koteswararaO',lastName:'perumalla'},
{userName:'as',firstName:'koteswararaoH',lastName:'perumalla'},
];
async.each(obj,function(item,callback){
MongoClient.connect(url,{ useNewUrlParser: true }, function(err, db) {
const DaTa = db.db("mydb");
const asa =item.userName; DaTa.collection("Campus").find({userName:item.userName}).toArray(function(err, result) {
if(result.length <=0){
DaTa.collection("Campus").insertMany(obj,function(err,result){
if(result){
return callback();
}
})
}
else{
DaTa.collection("Campus").updateOne({userName:item.userName},{$set:{"firstName":item.firstName}},function(er,result){
console.log(result +'1 record is updated')
if(result){
return callback();
}
})
}
db.close();
callback('Done');
})
});
},function(err,result){
console.log('completed')
})
I am using .each method of async package in Nodejs. I want to avoid insertion of the duplicate records to the MongoDB database.
Please tell me what part of my code should be changed for achieving async insertion of unique records.
You can define a unique index in MongoDB.
db.collectionName.createIndex( { "userName": 1 }, { unique: true } );
var DaTa;
MongoClient.connect(url,{ useNewUrlParser: true }, function(err, db) {
DaTa = db.db("mydb");
async.eachSeries(obj,function(item,callback){
console.log("*****************************")
const asa =item.userName;
// DaTa.createIndex( { "_id": 1 }, { unique: true } );
console.log("item: ",item)
DaTa.collection("Campus").find({userName:item.userName}).toArray(function(err, result) {
console.log(result.length)
console.log("result: ", result)
if(result.length <=0){
console.log("doc not found")
DaTa.collection("Campus").insert(item,function(err,result){
if(result){
callback();
}
})
}else{
console.log("doc found")
DaTa.collection("Campus").update({userName:item.userName},{$set:{"firstName":item.firstName}},function(er,result){
// console.log(result +'1 record is updated')
console.log("doc update result: ",result.result)
if(result) {
callback();
}
})
}
})
}, function(err,result){
console.log('############ completed ##################')
})
// db.close()
});
I want to increment id's automatically in the mongoDB while posting the data. I am able to attach date for the req.body. How to attach ids with auto incrementation?
This is my post call:
router.post('/addVisualization', function (req, res, next) {
MongoClient.connect(url, function (err, db) {
if (err) throw err;
var dbo = db.db(dbName);
req.body.dateOfEntry = new Date();
function getNextSequence(id) {
var ret = db.counters.findAndModify(
{
query: { _id: id },
update: { $inc: { seq: 1 } },
new: true
}
);
return ret.seq;
}
dbo.collection("visualization").insertOne(req.body, function (err, resDB) {
if (err) {
throw err;
res.status(401);
res.send({
"status": 401,
"message": "Some error happened"
});
}
else {
console.log("1 document inserted");
res.status(201)
res.send({
"body": req.body,
"status": 201,
"message": "visualization has been added"
});
}
});
db.close();
});
});
Try out the below code to auto increment id's in mongoDB.
router.post('/addVisualization', function (req, res, next) {
MongoClient.connect(url, {
useNewUrlParser: true
}, function (err, db) {
if (err) throw err;
var dbo = db.db(dbName);
req.body.dateOfEntry = new Date();
req.body.isDeleted = "false";
var countRow;
var sequenceDocument = dbo.collection("counterVisualization").findOneAndUpdate({
_id: "tid"
}, {
$inc: {
sequence_value: 1
}
}, {
new: true
});
dbo.collection("counterVisualization").find({
_id: "tid"
}).toArray(function (err, result1) {
if (err) {
throw err;
} else {
countRow = result1[0].sequence_value;
req.body["_id"] = countRow;
dbo.collection("visualization").insertOne(req.body, function (err, resDB) {
if (err) {
throw err;
res.status(401);
res.send({
"status": 401,
"message": "Some error happened"
});
} else {
console.log("1 document inserted");
res.status(201)
res.send({
"body": req.body,
"status": 201,
"message": "visualization has been added"
});
}
});
}
});
});
});
In mongo db you don't have a auto increment ids as mysql or oracle, Please take a look at this tutorial for how to do it out of the box.
Use a separate counters collection to track the last id of the sequence.
db.counters.insert(
{
_id: "userid",
seq: 0
}
)
db.counters.insert(
{
_id: "productid",
seq: 0
}
)
Create a getNextSequence function that accepts a name of the sequence.
function getNextSequence(name) {
var ret = db.counters.findAndModify(
{
query: { _id: name },
update: { $inc: { seq: 1 } },
new: true,
upsert : true // Creates a new document if no documents match the query
}
);
return ret.seq;
}
Use this getNextSequence() function during insert.
db.users.insert(
{
_id: getNextSequence("userid"),
name: "Mr. X",
// ... more fields
}
)
db.products.insert(
{
_id: getNextSequence("productid"),
name: "Mr. Y",
// ... more fields
}
)
Trying to follow the examples here to filter by using a projection to exclude _id. The _id still returns:
Code
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/db1";
MongoClient.connect(url, function (err, db) {
if (err) throw err;
var dbase = db.db("db1"); //here
dbase.collection("customers").find(
{},
{
_id: 0
}
).toArray(function(err, result) {
if (err) throw err;
console.log(result);
db.close();
});
});
Result still return as follows:
[ { _id: 5a2bb2d6ee48575cb54c4365,
name: 'John',
address: 'Highway 71' }, { _id: 5a2bb2d6ee48575cb54c436d,
name: 'Susan',
address: 'One way 98' }, .... { _id: 5a2bb2d6ee48575cb54c4371,
name: 'Chuck',
address: 'Main Road 989' }, { _id: 5a2bb2d6ee48575cb54c4372,
name: 'Viola',
address: 'Sideway 1633' } ]
Theoretically _id should not be part of what is returned. What is wrong here?
To limit the fields you have to use fields option( dont know about new updates):
dbase.collection("customers").find({}, {
fields: { _id: 0 }
}).toArray(function(err, result) {
if (err) throw err;
console.log(result);
db.close();
});
UPDATE:
For version > 3 you have to use projection option instead:
dbase.collection("customers").find({}, {
projection:{ _id: 0 }
}).toArray(function(err, result) {
if (err) throw err;
console.log(result);
db.close();
});
In version 3 of the MongoDB API, the fields option has been deprecated. You should now use the projection option instead.
For example:
dbase.collection('customers').find({}, {
projection: {
_id: 0
}
}).toArray(function (err, result) {
if (err) {
throw err
}
console.log(result)
db.close()
})
The full list of supported options can be found here: http://mongodb.github.io/node-mongodb-native/3.0/api/Collection.html#find
Starting in version 3.4, there is now an option for adding .project() outside of find().
Using ES8 async,await.
Ex:
async function connectDB(url) {
try {
const db = await MongoClient.connect(url);
const dbase = db.db("db1"); //here
const results = await dbase.collection("customers").find().project({_id:0}).toArray();
console.log(result);
db.close();
}
catch(err) {
throw err;
}
}
Docs here and another example here.
I'm using Node.js with mongodb.
var mongo = require("mongodb").MongoClient;
var url = process.env.MLAB_URI;
mongo.connect(url, function (err, db) {
if (err) {
console.log('Unable to connect to the mongoDB server. Error:', err);
} else {
//HURRAY!! We are connected. :)
console.log('Connection established');
var sequence = db.collection('sequence')
//Find and modify the sequence counter.
var obj = sequence.findAndModify({
query: {_id: 1},
update: { $inc: {seq: 1}},
new: true
});
console.log(obj);
sequence.find({_id:1}).toArray(function(err,res){
if(err)
console.log(err);
else
console.log(res)
});
db.close();
}
});
But the above code is not updating the database and the output of obj that is returned is Promise { <pending> } .
The complete output is
Connection established
Promise { <pending> }
[ { _id: 1, seq: 0 } ]
I need to update the value and retrieve the object . Is there any way to do that?
Thanks in advance!
Please change the findAndModify as mentioned below.
var obj = sequence.findAndModify(
{_id: 1},
{},
{ $inc: {"seq": 1}},
{new:true, upsert:true}
);
Second option to avoid promise:-
Comment the console.log(obj);
var obj = sequence.findAndModify(
{_id: "1"},
{},
{ $inc: {"seq": 1}},
{new:true, upsert:true}, function (err, doc) {
if(err)
console.log(err);
else
console.log(doc);
}
);
You are referring the Mongo shell version and try implementing the same using NodeJS version. The NodeJS findAndModify version is little different.
In order to get the old value of seq, you can set the new flag to false and doc.value.seq gives you the old value (i.e. value before update).
sequence.findAndModify(
{_id: "1"},
{},
{ $inc: {"seq": 1}},
{new:false, upsert:true}, function (err, doc) {
if(err)
console.log(err);
else {
console.log(doc);
console.log(doc.value.seq);
}
});
change to
var obj = sequence.findOneAndModify({
_id: 1,
update: { $inc: {seq: 1}},
upsert: true
});
I've been doing some research within these couple of days but got stuck while trying to test the codes that I got from the web.
var MongoClient = require('mongodb').MongoClient,
format = require('util').format;
MongoClient.connect('mongodb://127.0.0.1:27017/test', function(err, db) {
if (err) {
throw err;
} else {
console.log("successfully connected to the database");
db.collection('chat', function(err, collection) {
collection.find({}, {
tailable: true,
awaitdata: true,
numberOfRetries: -1
})
.sort({
$natural: 1
})
.each(function(err, doc) {
console.log(doc);
})
});
}
db.close();
});
And the error is:
c:\Project\node_modules\mongodb\lib\mongo_client.js:406
throw err
^
Am I missing any external library/reference because the error says "Cannot read property 'find' of undefined".
mongodb version: "2.0.31"
You check for a possible error in your first callback, but not the second one. Instead of
db.collection('chat', function(err, collection) {
collection.find({}, {...
Try:
db.collection('chat', function(err, collection) {
if (err) {
throw err;
} else {
collection.find({}, {...
This won't make your code snippet do what you want, but it will let you find out what error is preventing it from working.
You didnt export the collection module correctly....
If suppose your model class is collection.js,
then at the end of the class, it should be
module.exports = { Collection}
Final code will look like,
const mongoose = require('mongoose')
var Collection = mongoose.model('Collection', {
a: {type: String},
b: {type: String},
c: {type: Number},
}
module.exports = { Collection}
You can also do it like this:
collection.find((err, data) => {
if (err) {
console.log("An error: ", err);
} else {
console.log("My data", data);
}
});