Underscore's findWhere and MongoDB object - javascript

I use MongoDB and I want to use Underscore.js in my Angular app.
I have a model "Email" with the fields: "subject", "body" and "id".
This Email object looks like this in the browser console:
$$hashKey
"005"
_id
Object { $oid="5478774a6a61734d8a000000"}
body
"Here is the sample conte...le ble ble. Nice email."
subject
"This is first template"
This is the controller code in Angular:
$scope.viewEmail = function(emailId) {
var email = _.findWhere(emailData.data.emails, { _id: emailId });
console.log(email);
};
So, I just want to find an email with the specific id - the id I want to get is saved in a local variable emailId.
I should do something like that: _id.$oid: emailId but it causes a syntax error in the javascript console: "missing : after property id".

This will do the job:
_.find(list, predicate, [context])
Here is a fiddle:
http://jsfiddle.net/bqegdy2t/
var emailData = {
data: {
emails: [
{ _id: { $oid: "someId" }, body: "Hello Every Body1" },
{ _id: { $oid: "someOtherId" }, body: "Hello Every Body2" },
]
}
};
var emailId = "someId";
var email = _.find(emailData.data.emails, function(email) {
return email._id.$oid === emailId;
});
console.log(email);

the difficulty lies in the mongo objectid format that is an unusual JSON object containing string.
try _id: emailId versus _id.$oid: emailId
another option: dot notation often needs quotes around it "_id.$oid" : emailId especially those with dollar signs

Related

sendgrid mail sending error upon placing multiple receiver

I'm using const sgMail = require('#sendgrid/mail'); and utilizing sendgrid version 7.6.2.
When I'm adding two email addresses in array and passing that into send() or sendMultiple() it's throwing me error like this.
status: 'failed',
> Error: Error: String expected for `email`
here's the section where I'm putting the multiple emails,
mailsTo = {
email: ["demo#email.com", "demo1#email.com"],
name: "demo",
type: 'to'
}
here if I pass one email as in form of string the mail is getting triggered. Can anyone please suggest what am I doing wrong.
Thanks in advance
According to the documentation the addresses are to be passed as an array of EmailData (string or object with email and name).
Please try the following:
mailsTo = [
{
email: "demo#email.com",
name: "demo"
},
{
email: "demo1#email.com",
name: "demo"
}
]
Assuming mailsTo is being pass as the to parameter for

Upsert data with a dynamic field name

I just try to do something simple with Mongo but it doesn't work:
I want to upsert datas in an object like: module.xxx.yyy then I tried many things like :
UsersRights.upsert({
condoId: condoId,
userId: manager._id,
}, {
condoId: condoId,
userId: manager._id,
module: {
[defaultRight.xxx] : {
[defaultRight.yyy] : defaultRight.default
}
}
});
but when I want to add a new xxx or a new yyy, it will erase and replace the entire module object and not only add a new key.
I also tried this :
UsersRights.upsert({
condoId: condoId,
userId: manager._id,
}, {
condoId: condoId,
userId: manager._id,
["module." + defaultRight.module + "." + defaultRight.right] : defaultRight.default,
});
but the server show me an error like: MinimongoError: Key module.xxx.yyy must not contain '.'
You need to use the following form:
YourCollection.upsert({
_id: id, (can be other selectors as well)
}, {
$set: setter
});
Setter is an object you create before and should have the following form:
const setter = {};
setter[`${#1Level}.${#2Level}`] = data;
Where #1Level & #2Level are vars naming the fields you want to modify or to add.

Validating user using .pre save

My API accepts users POSTed as JSON. I would like to validate certain fields only if they are included as part of the JSON object.
For example, a user might look like this:
{
"email" : "test#test.com",
"username" : "testing",
"name" : "Test User"
}
or it might not have a name field:
{
"email" : "test#test.com",
"username" : "testing"
}
and I would like to make sure name has at least 6 characters if it is an included field.
I'm trying to build the validation process into my model using .pre but things aren't quite as I'd expect them.
var UserSchema = new Schema({
id : String,
name : String,
email : String,
username : String
},{ timestamps: { createdAt: 'created_at',updatedAt: 'updated_at' } });
UserSchema.pre('save', function(next) {
console.log(this); //no evidence of name property here
if("name" in this){
console.log("Name found"); //this is always the output
} else {
console.log("Name not found");
}
next();
});
The above code is for testing. Using either of the JSON objects above, the output is always "Name found" even though the object doesn't have a name property when I output to the console. Is this because the model has a name property?
You see the user object in the terminal and there is no property for name because the posted json might not have a name field as you mentioned, so you may do your logic/condition just when the name property is existed as follow:
UserSchema.pre('save', function(next) {
if (this.name !== undefined) {
if (this.name.length <= 6) {
// throw error or whatever
}
}
next();
});

Creating MongoDB Document from Nested Object

I'm sure it's a simple fix, but I've been pulling my hair out trying to get the syntax correct for a nested object. I'm trying to use it to create a MongoDB document.
The Mongo documents store conversations between two users. Each message in the conversation is stored in separate MongoDB documents, and the conversation document will reference each message that belongs to it.
Here's the Conversation Schema (which I think is OK)
var ConversationSchema = new mongoose.Schema({
participants: [
{
user1: {
id: {
type: mongoose.Schema.Types.ObjectId,
ref: "User"
},
username: String
},
user2: {
id: {
type: mongoose.Schema.Types.ObjectId,
ref: "User"
},
username: String
},
},
],
started: Number,
messages: [
{
type: mongoose.Schema.Types.ObjectId,
ref: "Message"
}
]
});
And here's one of my many attempts at creating the object to pass into MongoDB.
var conv = {
participants : {
"participants.user1.id" : req.body.senderId,
"participants.user1.username" : req.body.senderName,
"participants.user2.id" : req.body.recipientId,
"participants.user2.username" : req.body.recipientName
},
created : Date.now(),
messages : [] // The message _id is pushed in later.
}
It's the 'participants' bit which is really tripping me up. This data is coming back from the client as it should, but I can't manage to get it into my var conv. What's the correct syntax to create the nested object I need here?
Any guidance would be awesome! Thanks peoples!!
Fixed it! Yep it was just a simple syntax error: here's correct form in case anyone else ends up here.
var conv = {
participants : {
"user1" : {
"id" : req.body.senderId,
"username" : req.body.senderName
},
"user2" : {
"id" : req.body.recipientId,
"username" : req.body.recipientName
}
},
created : Date.now(),
messages : [] // The message _id is pushed in later.
}
Also, pro tip: Go away and do the washing up. Things will be much clearer when you come back to them.

Mongoose: CastError on querying incorrect ObjectId for nested object

I have following schema
var Topic= new Schema({
text: String,
topicId: String,
comments: [{type: Schema.Types.ObjectId, ref:'Comment'}]
});
var Comment = new Schema({
text: String
});
I am writing RESTFul API that will give me the Comment details as per topic ID and Comment ID
/topics/{id}/comments/{id}
Following is the function that gets data from Mongo
getCommentsById: function(req, resp){
req.db.Topic.findOne({"topicId": req.params.topicId})
.populate({path:"Comments", match:{"_id": req.params.commentId}})
.exec(function(err, topic){
if(err) {
return resp.status(500).json({
message: 'Error when getting Topic.',
error: err
});
}
if (!topic) {
return resp.status(404).json({
message: 'No such Topic'
});
}
if (!topic.comments || topic.comments.length==0) {
return resp.status(404).json({
message: 'No such Comment'
});
}
resp.json(topic.comments[0]);
});
}
The code works fine if I specify the right comment ID, but if I specify non-existing comment ID in URL then I get following error
{
"message": "Error when getting Topic.",
"error": {
"message": "Cast to ObjectId failed for value \"57c738b66d790f0c1bdb179\" at path \"_id\"",
"name": "CastError",
"kind": "ObjectId",
"value": "57c738b66d790f0c1bdb179",
"path": "_id"
}
}
What is the issue here and how to fix it?? Is there better way to query the required object?
The issue isn't that your specifying a non-existing comment ID. It's that you're specifying a string that can't be converted into a valid ObjectId. Your test string, "57c738b66d790f0c1bdb179" is a 23 character hex string. It should be length 24.
If you want to validate before attempting your query, there are several different ways you could go about it. Here's one example: Can I determine if a string is a MongoDB ObjectID?

Categories