Im trying to use .find({}) with mongogb and unfortunately its not giving me the response I was expecting, I'm unsure how to check if the document exists or not? What I'm trying to do is say:
If a document does exist then do something.. IE send a response back
but If a document doesn't exist then create the document,
unfortunately I know that a document doesnt exist yet it must be picking up the wrong thing with 'if (docs)' but then when I change it to something else then it always creates records!?
The code:
addRefund : (refundCalc, callback) => {
order_number = refundCalc.refundDetails.customer_details.order.order_number;
dbconnect.createConnection()
refund.find({order_number: order_number}, (err, docs) => {
if (docs) {
console.log('docss!!!!!!!!!!!!!' + JSON.stringify(docs));
console.log('calling within error!!!!!!')
let notStored = {"refundDocStored" : "False"}
callback(notStored)
dbconnect.closeConnection();
}
else {
refund.create(refundCalc).then((refunddoc) => {
let filestored = {"refundDocStored" : "True"}
dbconnect.closeConnection();
callback(filestored)
}).catch((err)=> {
console.log(err);
dbconnect.closeConnection();
})
}
})
},
the schema:
const refundSchema = new Schema({
domain : { type: String},
refundDetails : {
customer_details : [],
refund : {
shipping : {
amount : { type: Number},
tax : {type : Number},
maximum_refundable : {type : Number}
},
refund_line_items: [],
transactions: []
}
}
});
The orders are stored within the refundDetails like this:
"refundDetails":{"customer_details":{"order":{"order_number":1021
It simply doesnt seem to work for me! if a document exists i cant seem to actually prove that it does?
Any help would be great, thanks!
You are using the wrong search query. You are searching for order_number which is a property of an object inside another object. You have to reference the order_number full path in your query i.e {"refundCalc.refundDetails.customer_details.order.order_number" : order_number}
addRefund : (refundCalc, callback) => {
order_number = refundCalc.refundDetails.customer_details.order.order_number;
dbconnect.createConnection()
refund.find({"refundCalc.refundDetails.customer_details.order.order_number": order_number}, (err, docs) => {
if (docs) {
console.log('docss!!!!!!!!!!!!!' + JSON.stringify(docs));
console.log('calling within error!!!!!!')
let notStored = {"refundDocStored" : "False"}
callback(notStored)
dbconnect.closeConnection();
}
else {
refund.create(refundCalc).then((refunddoc) => {
let filestored = {"refundDocStored" : "True"}
dbconnect.closeConnection();
callback(filestored)
}).catch((err)=> {
console.log(err);
dbconnect.closeConnection();
})
}
})
},
Related
Using this node-ews package, I can send email, but I haven't been able to find a good example of how to read mails from the Inbox folder and get the email's text and attachments.
I've read the Microsoft documentation, such as this one: https://learn.microsoft.com/en-us/exchange/client-developer/exchange-web-services/how-to-work-with-exchange-mailbox-items-by-using-ews-in-exchange#get-an-item-by-using-the-ews-managed-api, but the examples are in C#, C++, or VB.
However, I would like to use Nodejs for this.
**I have found a best way extract every content using mailparser. see bellow
// At first Read emails from Inbox
const EWS = require('node-ews');
const simpleParser = require('mailparser').simpleParser;
// exchange server connection info
const ewsConfig = {
username: 'username',
password: 'password',
host: 'hostname'
};
const options = {
rejectUnauthorized: false,
strictSSL: false
};
// initialize node-ews
const ews = new EWS(ewsConfig, options);
var ewsFunction = 'FindItem';
var ewsArgs = {
'attributes': {
'Traversal': 'Shallow'
},
'ItemShape': {
't:BaseShape': 'Default'
},
'ParentFolderIds' : {
'DistinguishedFolderId': {
'attributes': {
'Id': 'inbox'
}
}
}
};
// Itreate over all the emails and store Id and ChangeKey.
ews.run(ewsFunction, ewsArgs, ewsSoapHeader)
.then(result => {
// Iterate over the result and extract Id and ChangeKey of the messages and pass those to GetItem function to read messages
})
// For reading individual messages returned by FindItem (using Id and ChangeKey)
var ewsFunction = 'GetItem';
var ewsArgs = {
'ItemShape': {
'BaseShape': 'Default',
'AdditionalProperties': {
'FieldURI': [
{ 'attributes': { 'FieldURI': 'item:MimeContent'}}
]
}
},
'ItemIds': {
'ItemId': {
'attributes': {
'Id': Id,
'ChangeKey': ChangeKey
}
}
}
};
await ews.run(ewsFunction, ewsArgs, ewsSoapHeader)
.then(result => {
// Iterate over the result and extract meesage
const {Message} = result.ResponseMessages.GetItemResponseMessage.Items
let mimeContent = Buffer.from(Message.MimeContent['$value'], 'base64').toString('binary');// decode mime content
simpleParser(mimeContent).then(async function (mail) {
console.log("mail")
console.log(mail.attachments)
console.log(mail.headers.get('message-id'))
console.log(mail.headers.get('references'))
console.log(mail.headers.get('in-reply-to'))
console.log({
// text: mail.text,
// html: mail.html ? mail.html.replace(/<meta([^>]+)>/g, "") : "",
from: (mail.from) ? mail.from.value.map(item => item.address) : [],
to: (mail.to) ? mail.to.value.map(item => item.address) : [],
cc: (mail.cc) ? mail.cc.value.map(item => item.address) : [],
bcc: (mail.bcc) ? mail.bcc.value.map(item => item.address) : [],
messageId: mail.messageId,
subject: mail.subject
})
}).catch((err) => {
console.log("err")
console.log(err)
})
})
Here you will get the full parsed mail contents with attachments. Happy Coding!!!
I combined two of my publications into a single one, as they were very similar. Both of them returned a set of cursor. I've rewritten them in low-level API, in order to make some control on data removing.
My problem is that, for a reason I totally ignore, the subscription onReady callback is never triggered. I've got other low-level pubsub in my app which publish data in a similar way and that works perfectly.
On the server, all my logs are correctly displayed, and no error is shown. The publication is runned correctly and the data are effectively sent to the client.
On the client, none of the onReady or onError callback is triggered.
Publication :
Meteor.publish("getTalkthread", function ( thread_id ) {
unblock(this);
console.log("start");
let uids = tags = corrections = [],
self = this;
let posts_cursor = Modules.both.queryGet({
type : 'posts',
method : 'find',
query : { $or: [
{ _id: thread_id },
{ parent: thread_id }
]
},
projection : { sort : { _id: 1 },
limit : 50
}
});
let posts_array = posts_cursor.fetch(),
posts_ids = posts_array.map( e => ( e._id ) );
//console.log("fetched posts", posts_array);
let corrs_cursor = Modules.both.queryGet({
type : 'corrections',
method : 'find',
query : { talkId: { $in: posts_ids } },
projection : { sort : { _id: 1 },
limit : 50
}
});
let corrs_array = corrs_cursor.fetch();
//console.log("fetched corrs", corrs_array);
let posts_authors = posts_array.map( e => ( e.owner ) ),
corrs_authors = corrs_array.map( e => ( e.owner ) );
let users_ids = _.union( posts_authors, corrs_authors );
let users_cursor = Modules.both.queryGet({
type : 'users',
method : 'find',
query : { _id: { $in: users_ids } },
projection : { sort : { date: -1 },
limit : 100,
fields : USER_PROFILE_FIELDS_
}
});
//console.log("fetched users", users_cursor.fetch());
let observers = {};
observers.posts = posts_cursor.observeChanges({
added : ( id, fields ) => { console.log("post added " + id); self.added ("posts", id, fields); },
changed : ( id, fields ) => { console.log("post changed " + id); self.changed("posts", id, fields); },
removed : ( id ) => {
console.log("test");
if ( id != thread_id ) {
console.log(true);
self.removed("posts removed " + id);
}
}
});
observers.users = users_cursor.observeChanges({
added : ( id, fields ) => { console.log("user added " + id); self.added ("users", id, fields); },
changed : ( id, fields ) => { console.log("user changed " + id); },
removed : ( id ) => { console.log("user removed " + id); }
});
observers.corrs = corrs_cursor.observeChanges({
added : ( id, fields ) => { console.log("corr added " + id); self.added ("corrections", id, fields); },
changed : ( id, fields ) => { console.log("corr changed " + id); self.changed("corrections", id, fields); },
removed : ( id ) => { console.log("corr removed " + id); self.removed("corrections", id); }
});
console.log("observers created");
this.ready();
self.onStop( () => {
observers.posts.stop();
observers.users.stop();
observers.corrs.stop();
});
console.log("end");
});
Subscription :
console.log("sub");
self.subscribe("getTalkthread", id, self.rerun.get()), {
onReady: function () {
console.log("READY");
if ( !Posts.findOne({ _id: id } )) {
$("#404NotFound").show();
$("#isoContent").hide();
} else if ( Posts.findOne( id ) ) {
$("#isoContent").show();
}
$("#spin").hide();
},
onError: function () {
console.log("ERROR");
$("#spin").hide();
$("#404NotFound").show();
$("#isoContent").hide();
}
};
The client page is correctly rendered, but the DOM manipulation are not triggered, forbidding the display of the content. Does anyone see what I'm doing wrong here ?
Thanks you
EDIT:
I tried to return an array of the three cursors, and, for whatever reason, the problem is the same. However, I don't see why.
Though I don't understand why, using Arunoda's SubsManager instead of the native Meteor.subscribe resolved the problem.
I'm trying to remove an object from an array of $oid from within a single document with mongoose using update.
Here is a hypothetical schema based on the schema I'm using now:
var TestSchema = Schema({
name: { type: String },
otherRefs: [ {type: Schema.ObjectId, ref: 'OtherSchema' } ]
});
An example document would look like (note: these aren't actual ObjectIDs from my db - I just randomly typed them in to give an idea of what the document would look like - the documents in my actual db have valid $oid values:
{ "_id" : { "$oid" : "56da0b6326008d0c24a4f029" },
"name" : "name1",
"otherRefs" : [
{"$oid" : "56c340259402505c2720541b"},
{"$oid" : "56c340259402505c2720541e"},
{"$oid" : "56c340259402505c2720541f"},
{"$oid" : "56d758862494c411001ca603"}
]
}
Here is the query I'm trying to use:
TestSchema.update(
{ '_id': testResult._id },
{ $pull: { 'otherRefs': { $oid : mongoose.Schema.ObjectId( refResult._id ) } } },
false,
true,
function(err, success) {
if (err) {
res.json(err);
} else {
res.json('success', success);
}
}
)
Have also tried { $pull: { 'otherRefs': refResult._id } } with no success.
testResult._id and refResult._id are received from previous queries.
Been at this for a while now and can't seem to wrap my head around this problem. Hoping someone can help me figure out what I'm doing wrong.
Thanks!
EDIT:
Now using:
TestSchema.update(
{ '_id': testResult._id },
{ $pull: { 'otherRefs': refResult._id ) } },
function(err, success) {
if (err) {
console.log(err);
} else {
console.log('Success');
}
}
)
The query doesn't hang anymore and "Success" is getting logged but nothing is changed in the actual document in DB.
I am using mongoose and I am facing a problem of creating a document if it does not exist, and if it exists, I want to update an array in the document.
For example, if I have
var courseSchema = new mongoose.Schema({
code : { type: String },
name : { type: String },
dept : { type: String },
instructors : [{ type : mongoose.Schema.ObjectId, ref: 'User' }],
});
var Course = mongoose.model('Course', courseSchema);
...
...
// This code should check if a course exists with a specified 'code' and
// 'name' and , if it exist, I want to add req.body.instructor_id to
// instructor array in that document, else I want to create a document with
// the specified course, name(and dept) and with req.body.instructor_id as the only element in
// the instructors array
// So far I have this, but it is clearly wrong.
Course.findOneAndUpdate(
{code: req.body.code, name: req.body.name},
{$push: {instructors: req.user._id}},
{upsert: true},
function (err, course) {
if (err)
console.log("error " + err);
else {
console.log(JSON.stringify(course, null, '\t'));
}
}
);
The second parameter should be the whole object, not only instructors. For example:
function findOneAndUpdateCourse(req, callback){
Course.findOneAndUpdate(
{code: req.body.code, name: req.body.name},
{
$setOnInsert: { code: req.body.code},
$setOnInsert: { name: req.body.name},
$push: {instructors: req.user._id}}
},
{upsert: true},
function (err, course) {
if (err)
console.log("error " + err);
else {
console.log(JSON.stringify(course, null, '\t'));
}
}
);
}
var urlSchema = new Schema ( {
url : String,
visitor : [{name: String,date: Date}],
counter : Number
});
var url = mongoose.model('url',urlSchema);
var domain = blah blah;
var conditions = { url: domain };
var update = { $inc : {counter:1},
$push : { visitor: [{
name: data.username,
date: new Date()
}]
}
};
var options = {upsert: true};
url.update(conditions,update,options,function(err){
if(err){
console.log(err);
}else{
console.log('A domain successfully added to DB');
}
Currently I am using the schema and code above to make an access counter for each page.
It upserts url documents which is counting total access and holding access user info.
so far so good It's working properly.
now I want to add "counter : Number" in visitor array and when the event occurs, if the user is already in visitor array,I want to update that instead of pushing new one.
But I have no idea how to make the 'double upsert' command.
is there anyway to do that?
It may be a bit difficult even impossible perform a query that satisfy your condition. I have reproduced your scenario with following query
url.findOne({'url': 'search.php', 'visitor.name': "JohnDoe"},
function (err, visitor) {
if (visitor) {
url.update(
{
'url': 'search.php', 'visitor.name': "JohnDoe"
},
{
$inc: {'visitor.$.counter': 1, 'counter': 1}
},
function(err, result) {
if (err) {
console.log("Error occured")
} else {
console.log("Success");
}
});
} else {
var conditions = { url: 'search.php' };
var update = { $inc : {counter:1},
$push : { visitor: [{
name: data.username,
date: new Date(),
counter: 0
}]
}
};
var options = {upsert: true};
url.update(conditions,update,options,function(err){
if(err){
console.log(err);
}else{
console.log('A domain successfully added to DB');
}
});
}
}
);
Simple, insert if not exists with counter = 0, update if exists with incrementing counter by 1