how to set variable value in query function? - node.js

1.here i need "did" value outside if condition but when it's going in IF and execute query than it's not setting up the value of did which I define in function "did = doc.value.seqValue" getting undefined.
2. else working fine.
var did;
if (documents[0] == null) {
dbo
.collection("Domain")
.findOneAndUpdate(
{ _id: "Did" },
{ $inc: { seqValue: 1 } },
function (err, doc) {
if (err) throw err;
dbo.collection("Domain").insertOne(
{
_id: doc.value.seqValue,
UserID: parseInt(req.body.userid),
ClientID: parseInt(req.body.clientid),
Domain: req.body.domain,
IsDeleted: false,
CreatedBy: parseInt(createdby),
CreatedDate: new Date(),
LastUpdatedDate: null,
LastUpdatedBy: null,
},
function (err, data) {
if (err) throw err;
did = doc.value.seqValue;
}
);
}
);
} else {
did = documents[0].DomainID;
}

Related

Check for subdocument is deleted or not in node.js [duplicate]

Chatrooms.findOneAndUpdate({Roomname: room.Roomname},{ $setOnInsert: {status: true, userNum: 1}}, {new: true, upsert: true}, function(err, doc) {
if(err) console.log(err);
console.log("DOC " + doc)
if(doc.status) {
// FOUND ROOM SATTUS IS TRUE LOGIC
console.log(doc);
// return callback(true)
}
});
Above query will return to me the actual document that's updated or inserted but I can't check exactly which one it is. If I do an update instead of findOneandUpdate I'm returned this
{
ok: 1,
nModified: 0,
n: 1,
upserted: [ { index: 0, _id: 55df883dd5c3f7cda6f84c78 } ]
}
How do I return both the document and the write result or at least the upserted field from the write result.
As of 8 August 2019 (Mongoose Version 5.6.9), the property to set is "rawResult" and not "passRawResult":
M.findOneAndUpdate({}, obj, {new: true, upsert: true, rawResult:true}, function(err, d) {
if(err) console.log(err);
console.log(d);
});
Output:
{ lastErrorObject:
{ n: 1,
updatedExisting: false,
upserted: 5d4befa6b44b48c3f2d21c75 },
value: { _id: 5d4befa6b44b48c3f2d21c75, rating: 4, review: 'QQQ' },
ok: 1 }
Notice also the result is returned as the second parameter and not the third parameter of the callback. The document can be retrieved by d.value.
Version 4.1.10 of Mongoose has an option called passRawResult which if set to true causes the raw parameter to be passed. Leaving out this option seems to default to false and cause raw to always be undefined:
passRawResult: if true, passes the raw result from the MongoDB driver
as the third callback parameter
http://mongoosejs.com/docs/api.html#query_Query-findOneAndUpdate
Alright so my main problem was that I couldn't get the _id of the document I inserted without not being able to check whether if it was updated/found or inserted. However I learned that you can generate your own Id's.
id = mongoose.Types.ObjectId();
Chatrooms.findOneAndUpdate({Roomname: room.Roomname},{ $setOnInsert: {_id: id, status: true, userNum: 1}}, {new: true, upsert: true}, function(err, doc) {
if(err) console.log(err);
if(doc === null) {
// inserted document logic
// _id available for inserted document via id
} else if(doc.status) {
// found document logic
}
});
Update
Mongoose API v4.4.8
passRawResult: if true, passes the raw result from the MongoDB driver as the third callback parameter.
I'm afraid Using FindOneAndUpdate can't do what you whant because it doesn't has middleware and setter and it mention it the docs:
Although values are cast to their appropriate types when using the findAndModify helpers, the following are not applied:
defaults
Setters
validators
middleware
http://mongoosejs.com/docs/api.html search it in the findOneAndUpdate
if you want to get the docs before update and the docs after update you can do it this way :
Model.findOne({ name: 'borne' }, function (err, doc) {
if (doc){
console.log(doc);//this is ur document before update
doc.name = 'jason borne';
doc.save(callback); // you can use your own callback to get the udpated doc
}
})
hope it helps you
I don't know how this got completely off track, but there as always been a "third" argument response to all .XXupdate() methods, which is basically the raw response from the driver. This always tells you whether the document is "upserted" or not:
Chatrooms.findOneAndUpdate(
{ "Roomname": room.Roomname },
{ "$setOnInsert": {
"status": true, "userNum": 1
}},
{ "new": true, "upsert": true },
function(err, doc,raw) {
if(err) console.log(err);
// Check if upserted
if ( raw.lasErrorObject.n == 1 && !raw.lastErrorObject.updatedExisting ) {
console.log("upserted: %s", raw.lastErrorObject.upserted);
}
console.log("DOC " + doc)
if (doc.status) {
// FOUND ROOM SATTUS IS TRUE LOGIC
console.log(doc);
// return callback(true)
}
});
Which will tell you the _id of the document that was just upserted.
From something like this in the "raw" response:
{ lastErrorObject:
{ updatedExisting: false,
n: 1,
upserted: 55e12c65f6044f57c8e09a46 },
value: { _id: 55e12c65f6044f57c8e09a46,
status: true,
userNum: 1
__v: 0 },
ok: 1 }
Complete reproducible listing:
var async = require('async'),
mongoose = require('mongoose'),
Schema = mongoose.Schema;
mongoose.connect('mongodb://localhost/test');
var testSchema = new Schema({
name: String
});
var Test = mongoose.model('Test', testSchema, 'test');
async.series(
[
function(callback) {
Test.remove({},callback);
},
function(callback) {
async.eachSeries(
["first","second"],
function(it,callback) {
console.log(it);
Test.findOneAndUpdate(
{ "name": "Bill" },
{ "$set": { "name": "Bill" } },
{ "new": true, "upsert": true },
function(err,doc,raw) {
console.log(raw),
console.log(doc),
callback(err);
}
);
},
callback
);
}
],
function(err) {
if (err) throw err;
mongoose.disconnect();
}
);
Which outputs:
first
{ lastErrorObject:
{ updatedExisting: false,
n: 1,
upserted: 55e2a92328f7d03a06a2dd6b },
value: { _id: 55e2a92328f7d03a06a2dd6b, name: 'Bill', __v: 0 },
ok: 1 }
{ _id: 55e2a92328f7d03a06a2dd6b, name: 'Bill', __v: 0 }
second
{ lastErrorObject: { updatedExisting: true, n: 1 },
value: { _id: 55e2a92328f7d03a06a2dd6b, name: 'Bill', __v: 0 },
ok: 1 }
{ _id: 55e2a92328f7d03a06a2dd6b, name: 'Bill', __v: 0 }

How to perform update in mongoose

I am trying to update my record,but its not happening in my case and i am not sure about the case where it went rong,can any one suggest me help.Thanks
My mongoose code,
exports.updatestudent = function (req, res) {
var student = new Student(req.body);
var data = {};
var id = req.params;
var params = req.body;
var item = {
'name': params.name,
'rollnumber': params.rollnumber,
'class': params.class,
'city': params.city
};
Student.update({ _id: id },{ $set: item }, function (err, result) {
if (err) {
console.log('err');
}
if (result) {
data = { status: 'success', error_code: 0, result: result, message: 'Article updated successfully' };
res.json(data);
}
});
};
my schema,
var StudentSchema = new Schema({
name: {
type: String
},
rollnumber: {
type: String
},
class: {
type: String
},
city: {
type: String
},
status: {
type: String
},
_id: {
type: Schema.ObjectId
}
});
/**
* Hook a pre validate method to test the local password
*/
mongoose.model('student', StudentSchema, 'student');
my result in postman,
{
"status": "success",
"error_code": 0,
"result": {
"ok": 0,
"n": 0,
"nModified": 0
},
"message": "Article updated successfully"
}
I am trying to update my record,but its not happening in my case and i am not sure about the case where it went rong,can any one suggest me help.Thanks
It seems you forgot to specify the key.
Replace
var id = req.params;
By
var id = req.params.id;
Make sure that you are getting your id in var id = req.params;
And I am sure you will not get your id like this
check your req.params; values and give your correct id in the query
Update
var item = {};
if (params.name) {
item.name = params.name;
}
if (params.rollnumber) {
item.rollnumber = params.rollnumber
}
Student.update({
_id: id
}, {
$set: item
}, function(err, result) {
if (err) {
console.log('err');
}
if (result) {
data = {
status: 'success',
error_code: 0,
result: result,
message: 'Article updated successfully'
};
res.json(data);
}
});

How to setup sequelize orm in nodejs

In the model :
var Sequelize = require('sequelize');
var sequelize_config = {
"username": process.env.DB_USERNAME || "root",
"password": process.env.DB_PASSWORD || "",
"pool": 200,
"database": "faasos_platform",
"host": "localhost",
"dialect": "mysql",
"dialectOptions": {
"multipleStatements": true
},
"logging": true,
"define": {
"timestamps": true,
"underscored": true
}
}
var sequeliz = new Sequelize(sequelize_config.database, sequelize_config.username, sequelize_config.password, sequelize_config);
module.exports = function (sequeliz, DataTypes) {
var auth = sequeliz.define("auth", {
device_id: {
type: DataTypes.STRING(50),
validate: {
notEmpty: true
}
},
customer_id: {
type: DataTypes.INTEGER,
validate: {
notEmpty: true
}
},
created_at: {
type: DataTypes.DATE,
validate: {
notEmpty: true
}
},
access_token: {
type: DataTypes.STRING(455),
validate: {
notEmpty: true
}
},
ip_address: {
type: DataTypes.STRING(20),
validate: {
notEmpty: true
}
},
is_active: {
type: DataTypes.INTEGER,
validate: {
notEmpty: true
}
}
}, {
classMethods: {
associate: function (models) {},
verify_user: function (req, callback) {
var d = new Date();
var sql = " Select customer_id From auth WHERE access_token =:access_token && is_active = '1' ";
sequelize.query(sql, {
replacements: {
access_token: req.access_token
},
raw: true
}).spread(function (data, metadata) {
callback(null, data);
}).catch(function (err) {
callback(err, null);
});
},
revoke_access_token: function (req, callback) {
var sql = "UPDATE auth SET is_active = 0 " +
"WHERE customer_id = :customer_id";
sequelize.query(sql, {
replacements: {
customer_id: req.id
},
raw: true
}).spread(function (data, metadata) {
callback(null, data);
}).catch(function (err) {
callback(err, null);
});
},
save_access_token_details: function (req, callback) {
var d = new Date();
var sql = "INSERT INTO auth (device_id, customer_id, created_at, access_token, ip_address, is_active)" +
"VALUES (:device_id, :cust_id, :created_at, :access_token, :ip_add, 1) ";
sequelize.query(sql, {
replacements: {
device_id: req.device_code ,
cust_id: req.id ,
created_at: d,
access_token: req.access_token,
ip_add: req.ip_add
},
raw: true
}).spread(function (data, metadata) {
callback(null, data);
}).catch(function (err) {
callback(err, null);
});;
}
},
tableName: 'auth',
timestamps: true,
underscored: true
});
return auth;
};
In my controller :
var models = require('../models/auth.js'); // the above model is saved in file auth.js
models.auth.verify_user(access_token, function (err, data) {
if (err) {
res.status(401).send({
'err': 'Unauthorized!'
});
}
if (data) {
models.revoke_access_token(user, function (err, data) {
if (err) {
res.status(401).send({
'err': 'Unauthorized!'
});
}
});
}
models.save_access_token_details(payload, function (err, data) {
if (err) {
res.status(401).send({
'err': 'Unauthorized!'
});
} else {
console.log(err, data);
res.send(data);
}
});
});
But each time it exists with the error ::
TypeError: Cannot call method 'verify_user' of undefined
at SignStream. (/home/salim/Documents/proj/platform/oAuth/controllers/validate.js:25:19)
at SignStream.EventEmitter.emit (events.js:95:17)
at SignStream.sign (/home/salim/Documents/proj/platform/oAuth/node_modules/jsonwebtoken/node_modules/jws/lib/sign-stream.js:54:8)
at SignStream. (/home/salim/Documents/proj/platform/oAuth/node_modules/jsonwebtoken/node_modules/jws/lib/sign-stream.js:37:12)
at DataStream.g (events.js:180:16)
at DataStream.EventEmitter.emit (events.js:92:17)
at DataStream. (/home/salim/Documents/proj/platform/oAuth/node_modules/jsonwebtoken/node_modules/jws/lib/data-stream.js:20:12)
at process._tickCallback (node.js:415:13)
stream.js:94
throw er; // Unhandled stream error in pipe. ^
Error: read ECONNRESET
at errnoException (net.js:901:11)
at Pipe.onread (net.js:556:19)
Please help where am I going wrong ?? Why is the orm not able to recognize the function ????
Your problem is that models.auth is undefined after you initialize models. Since models.auth is undefined, you cannot call its functions and cannot use its members.
auth is a local variable inside module.exports. Even though you return it, outside its scope you cannot use it.
If require calls module.exports, then your models is the very same object as auth, since you returned auth, therefore models.verify_user is existent in your code. However, I propose the following fix:
var models = {}; //creating an empty object which will hold the models
models.auth = require('../models/auth.js'); // the above model is saved in file auth.js
and then you will be able to use models.auth.

How to handle error when MongoDB collection is updating in JavaScript(Node.js)

I've been trying get an error when running bad code. The following code tries to update a record which has _id value 5. There is actually no such record, but I can't catch any error messages with the following function.
What should I do?
collection.update(
{ _id : "5" },
// { _id : req.session.User._id },
{ $set: { password : req.param('password') } },
{ writeConcern: { w: "majority", wtimeout: 3000 } },
function(err, result) {
if (err) { console.log(err); return err; }
res.send("/user/show");
}
);
The callback of update() has 2 arguments, err and result. When the item is updated, result is set to true, false otherwise. So when the item is not updated because item is not found, it's not considered an error, so err is null. if (err) won't be true. You need to test for updated this way:
collection.update(
{ _id : "5" },
// { _id : req.session.User._id },
{ $set: { password : req.param('password') } },
{ writeConcern: { w: "majority", wtimeout: 3000 } },
function(err, result) {
if (err) { console.log(err); res.send(err); return;}
if (result) {
res.send("/user/show");
} else {
res.send("/user/notshow");
}
);

MongoClient Native FindAndModify "Need update or remove" Error

My node.js client looks like this:
var MongoClient = require('mongodb').MongoClient;
MongoClient.connect(mongoendpoint, function(err, db) {
if(err) throw err;
var collection = db.collection('test-collection');
var ws = new WebSocket(websocket_Endpoint);
ws.on('open', function() {
log.info('Connected.');
});
ws.on('message', function(data, flags) {
wsevent = JSON.parse(data);
var args = {
'query': {
id: '1.2.3.4'
},
'update': {
$set: {
lastseen: "201405231344"
},
$addToSet: {
record: "event123"
}
},
'new': true,
'upsert': true
};
collection.findAndModify(args, function(err, doc){
log.info(err);
});
});
});
When I run this, I get the following error:
info: name=MongoError, ok=0, errmsg=need remove or update
I can't figure out why. I can run the exact same args json above using RoboMongo and the query works just fine.
Robomongo Query
db['test-collection'].findAndModify({"query":{"id":"1.2.3.4"},"update":{"$setOnInsert":{"lastseen":"201405231344"},"$addToSet":{"record":"event123"}},"new":true,"upsert":true});
What am I missing?
Your args section is wrong, it should be an array and does not need key values for "query" and "update". And the "options" value also needs to be an object (sub-document):
var args = [
{ id: '1.2.3.4' },
{
$set: {
lastseen: "201405231344"
},
$addToSet: {
record: "event123"
}
},
{
'new': true,
'upsert': true
}
];
Or specifically in the call:
collection.findAndModify(
{ id: '1.2.3.4' },
{
$set: { lastseen: "201405231344" },
$addToSet: { record: "event123" }
},
{
'new': true,
'upsert': false
},
function(err, doc){
Examples are also included on the manual page.

Resources