How to get last inserted id in node.js from mongodb.
My code is as follow:
var insertDocument = function(db, callback) {
db.collection('feedback_replies').insertOne( {
"feedback_id" : req.body.id,
"reply_text" : req.body.reply,
"replied_by" : "admin",
"replied_at" : new Date()
}, function(err, result) {
console.log("Record added as "+result);
assert.equal(err, null);
callback();
});
};
MongoClient.connect(url, function(err, db) {
assert.equal(null, err);
insertDocument(db, function() {
db.close();
});
});
I have created collection feedback_replies in which I insert. I want to get last inserted id from collection.
you can get the _id in the callback result as:
var insertDocument = function(db, callback) {
db.collection('feedback_replies').insertOne( {
"feedback_id" : req.body.id,
"reply_text" : req.body.reply,
"replied_by" : "admin",
"replied_at" : new Date()
}, function(err, result) {
console.log("Record added as "+result.insertedId);
assert.equal(err, null);
callback();
});
};
get full record what you have inserted as :
console.log("record inserted >>"+JSON.stringify(result.ops[0]));
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 ?
I need to store one record in three different collections at the same time, but I need that if just one of this operations fails (for any kind of reasons) the entire procedure will be canceled. In a few words, I need to be sure that this record is stored correctly in each all the three collections: I need to avoid the situation where the record is stored in just two (or one) collections.
This is my actual code:
var insertOne = function(data) {
req.app.locals.db.collection('document_1').findOneAndUpdate({'id': data.id}, {$set: {'element': 'data.element}}, {returnOriginal: false}, function(err, result) {
if (err) {
console.log('error 1');
return;
}
if(result) insertTwo(data);
});
}
var insertTwo = function(data) {
req.app.locals.db.collection('document_2').findOneAndUpdate({'id': data.id}, {$set: {'element': 'data.element}}, {returnOriginal: false}, function(err, result) {
if (err) {
console.log('error 2');
return;
}
if(result) insertThree(data);
});
}
var insertThree = function(data) {
req.app.locals.db.collection('document_2').findOneAndUpdate({'id': data.id}, {$set: {'element': 'data.element}}, {returnOriginal: false}, function(err, result) {
if (err) {
console.log('error 3');
return;
}
if(result) console.log('success!');
});
}
insertOne(mydata);
Thanks.
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
});
In node.js I am writing query to insert document to collection, but that query inserting only one document. Below the js code is,
app.js
router.post('/creatList', function(req,res){
console.log(req.body.email);
var emails = req.body.email;
if(req.body.wData.wishListType == 'Shared'){
var findUsers = function(db, callback) {
var cursor;
cursor = db.collection('users').find({email: { $in: emails }})
cursor.toArray(function(err, docs){
if(err){
callback(new Error("Some problem"));
} else {
callback(null,docs);
}
});
};
MongoClient.connect(config.database, function(err, db) {
assert.equal(null, err);
findUsers(db, function(err,docs) {
db.close();
console.log(docs);
var inserts_processing = 0;
for(var key in docs){
console.log(key);
var ids = docs[key]._id;
inserts_processing++;
console.log(ids);
var insertDocument = function(db, callback) {
db.collection('notifications').insertOne({
"userId" : ids,
},function(err, result) {
inserts_processing--;
assert.equal(err, null);
console.log("Inserted a document into the notifications collection.");
if(inserts_processing == 0){
db.close();
callback();
}
});
};
MongoClient.connect(config.database, function(err, db) {
assert.equal(null, err);
insertDocument(db, function() {
db.close();
});
});
}
});
});
} else {
console.log("other");
}
});
In the above code console.log contains two ids 570dec75cf30bf4c09679deb
56fe44836ce2226431f5388f but actually it inserting only last one.
According to your updated code I will try the following
router.post('/creatList', function(req,res){
console.log(req.body.email);
var emails = req.body.email;
if(req.body.wData.wishListType == 'Shared'){
// Open one connection to find users and insert documents
MongoClient.connect(config.database, function(err, db) {
assert.equal(null, err);
if(!err){
findUsers(db, function(err,docs) {
if(!err){
insertDocs(db, docs, function(){
db.close(); // Close connection
console.log("All documents have been inserted");
res.status(200).send("All is OK");
});
}
});
});
}
} else
console.log("other");
});
function insertDocs(db, docs, callback){
var inserts_processing = 0; // Will contain the number of inserts pending operation
for(var key in docs){
var ids = docs[key]._id;
inserts_processing++; // Before writing data, add one to processing inserts
db.collection('notifications').insertOne({
"userId" : ids,
}, function(err, result) {
inserts_processing--; // One insert have been finished, so remove one
assert.equal(err, null);
console.log("Document inserted into the notifications collection.");
// If all inserts have been finished, call back the function
if(inserts_processing == 0)
callback();
});
}
}
function findUsers(db, callback) {
var cursor;
cursor = db.collection('users').find({email: { $in: emails }})
cursor.toArray(function(err, docs){
if(err)
callback(new Error("Some problem"));
else
callback(null,docs);
});
};
I am trying to delete items from different documents in mongodb with one http.delete call. Here is the code I have written but it is just deleting item from the first document not from the other two documents. Here is the code I have written:
app.delete('/deleteActor/:productName/:actor', function(req, res) {
console.log("Deleting Actor" + req.params.productName + ":" + req.params.actor);
impactMapActor.update({productName:req.params.productName}, { $pull: { actor:req.params.actor}},function (err, data) {
if (err)
//{
res.send(err);
console.log(err);
impactMapActivity.remove({productName:req.params.productName},{actor:req.params.actor},function (err, data) {
impactMapFeature.remove({productName:req.params.productName},{actor:req.params.actor},function (err, data) {
});
});
impactMapActor.find({
productName : req.body.productName
}, function(err, data) {
if (err)
res.send(err);
console.log("Printing Data" + data)
res.json(data);
});
});
});
Here is my schema of other two documents:
module.exports = mongoose.model('ImpactMapActivity', {
productName:String,
actor: String,
activity: [{ type:'String' }],
});
module.exports = mongoose.model('ImpactMapFeature', {
productName: String,
actor: String,
activity: String,
feature: String,
issueKey: String
});
You have to add option multi : true to your query to tell mongo to update multiple documents like this:
impactMapActor.update({productName:req.params.productName}, { $pull: {actor:req.params.actor}},{multi:true},function (err, data) {
});