How do I access and update nested Mongoose documents - javascript

I have a mongoose document that is a User. Each user has arrays or words e.g. nouns. I want to be able to update the fields of the words e.g. add a +1 to the frequency or change the status number. I can access the whole array but not the individual items in the array. Also i want to be able to display the items in the array based on their fields e.g. only display those with frequency of 3 or more etc...
I have tried lots of different things but I'm just not getting it. I keep getting back error messages that findOneAndUpdate is not a function, or 'undefined' when I try to access and update documents.
{
"_id" : ObjectId("5f7d8490c1842471c6bcea42"),
"username" : "eric#mail.com",
"nouns" : [
{
"_id" : ObjectId("5f7d849cc1842471c6bcea43"),
"word" : "die Sonne",
"timeStamp" : ISODate("2020-10-07T09:04:28.436Z"),
"frequency" : 0,
"status" : 0
},
{
"_id" : ObjectId("5f7d84a8c1842471c6bcea45"),
"word" : "das Wetter",
"timeStamp" : ISODate("2020-10-07T09:04:40.940Z"),
"frequency" : 0,
"status" : 0
},
{
"_id" : ObjectId("5f7d84afc1842471c6bcea47"),
"word" : "der Apfel",
"timeStamp" : ISODate("2020-10-07T09:04:47.403Z"),
"frequency" : 0,
"status" : 0
},
{
"_id" : ObjectId("5f7d84b9c1842471c6bcea49"),
"word" : "das Maedchen",
"timeStamp" : ISODate("2020-10-07T09:04:57.388Z"),
"frequency" : 0,
"status" : 0
},
{
"_id" : ObjectId("5f7d84c8c1842471c6bcea4b"),
"word" : "das Auto",
"timeStamp" : ISODate("2020-10-07T09:05:12.036Z"),
"frequency" : 0,
"status" : 0
}
],
"verbs" : [],
"adjectives" : [],
"others" : [],
"salt" : "*****",
"hash" : "*****",
"__v" : 5
}

figured it out after hours
const ObjectId = require('mongodb').objectID
db.collections.users.updateOne(
{},
{$set: {"nouns.$[element].status": 3}},
{multi: true,
arrayFilters: [{"element._id":
ObjectId(req.body.inputId)}]}
);

Related

Not getting the object key value using javascript

I am trying to read some key-value from one object using Javascript but one key value is not reading at all. I am explaining my code below.
customer={
"_id" : ObjectId("5e21bdb921a1de5a8885c368"),
"IsActive" : true,
"GroupName" : "ashok",
"CustomerId" : "7008980097Saikantassss#okedqart",
"GroupCode" : "ashokgrp",
"GroupType" : "Group",
"GroupDescription" : "test description",
"GroupImage" : "",
"StoreCode" : "DKWF",
"GroupID" : "1673e78b-8d35-4c5b-9bda-35d8788a64ad",
"CreatedAt" : ISODate("2020-01-17T13:59:21.373Z"),
"UpdatedAt" : ISODate("2020-01-17T13:59:21.373Z"),
"__v" : 0
}
Here I have the above fetched value from mongodb but when I am printing the customerId value like below.
console.log(customer['CustomerId']);
//undefined
The above value is coming undefined but same time console.log(customer['GroupCode']); giving the value as ashokgrp. Here I need to print also customer['CustomerId'] value.
var customer={
"_id" : "5e21bdb921a1de5a8885c368",
"IsActive" : true,
"GroupName" : "ashok",
"CustomerId" : "7008980097Saikantassss#okedqart",
"GroupCode" : "ashokgrp",
"GroupType" : "Group",
"GroupDescription" : "test description",
"GroupImage" : "",
"StoreCode" : "DKWF",
"GroupID" : "1673e78b-8d35-4c5b-9bda-35d8788a64ad",
"CreatedAt" : "2020-01-17T13:59:21.373Z",
"UpdatedAt" : "2020-01-17T13:59:21.373Z",
"__v" : 0
}
console.log(customer.CustomerId);
It Will work .

MongoDB - Finding the parent object based on a very nested property

I have a collection that consists of posts. Inside those post objects are properties about the post, one of which being an array of tags associated with the post. Inside the array of tags are more objects, each of which are the tags with a name property. I would like to get back all the posts from this collection which have a given tag in them based on the name of the tag.
Here is an example of a post object within the collection:
{
"_id" : ObjectId("5c6a0478cba09c148b497fc6"),
"tags" : [
{
"_id" : "5c69d974e05511106048780e",
"name" : "Food",
"text_color" : "#ffffff",
"bg_color" : "#02569b",
"createdAt" : "2019-02-17T22:00:20.143Z",
"updatedAt" : "2019-02-17T22:00:20.143Z",
"__v" : 0
},
{
"_id" : "5c69d95de05511106048780d",
"name" : "Drinks",
"text_color" : "#ffffff",
"bg_color" : "#0175c2",
"createdAt" : "2019-02-17T21:59:57.758Z",
"updatedAt" : "2019-02-17T21:59:57.758Z",
"__v" : 0
}
],
"title" : "Title of the post",
"body" : "body of the post",
"author_id" : ObjectId("5c5e0d3b647f12e949cbea1e"),
"author_name" : "garrett",
"likes_count" : 1,
"createdAt" : ISODate("2019-02-18T01:03:52.497Z"),
"updatedAt" : ISODate("2019-02-28T00:25:21.969Z"),
"__v" : 0,
"dislikes_count" : 0
}
Of course I have other post objects in this collection, some of which may have different tags. How can I get all posts with the food tag to be returned?
A basic find query will do the job here. Here's how it looks
const tagName = 'food;
db.posts.find({ 'tags.name': tagName }).then(console.log);

Node.js update element in MongoDB

I have the following Mongoose schema and model:
var deviceSchema = new Schema({
deviceId:String,
deviceName:String,
devicePlace:String,
socket : [{number: Number,name:String, state : Boolean, current: Number, image:Number,locked:Boolean,reserved:Boolean}]
});
I already have a device in my database with four sockets.
Here example!
This is original data.
{
"_id" : ObjectId("5626569006bc3da468bafe93"),
"deviceId" : "0013A20040B5769A",
"deviceName" : "device",
"devicePlace" : "place",
"__v" : 0,
"socket" : [
{
"_id" : ObjectId("5628bd83570be84e28879e2d"),
"number" : 0,
"name" : "name"
"state" : true,
"current" : 0
"image" : 0,
"locked" : false,
"reserved" : false,
}, ...
]
}
and I received data from client for update.
{
"_id" : ObjectId("5626569006bc3da468bafe93"),
"deviceId" : "0013A20040B5769A",
"__v" : 0,
"socket" : [
{
"_id" : ObjectId("5628bd83570be84e28879e2d"),
"number" : 0,
"name" : "new name!!!!!"
"state" : true,
"current" : 0
}, ...
]
}
Now I'm trying to update a specific socket's name in the database with the following command:
device.update({deviceId: newData.deviceId, "socket.number": newData.number}, {$set: {"socket.$.name": newData.name}})
newData is object that extracted from socket array in received data.
I want to just update first socket's name.
or if possible, I want to update every socket's name as received socket array.
But this does not seem to be working, but I get no error. Can someone pin point what I'm doing wrong?
Add the callback to the update statement to see the error trace.
device.update({deviceId:newData.deviceId,'socket.number':newData.number}
,{$set: {"socket.$.name" : newData.name}}
,function(error,updatedDevice){
if(error) throw error;
// or : console.log("update error",error.message);
})

Node.js update elements in MongoDB

I have the following Mongoose schema and model:
var deviceSchema = new Schema({
deviceId:String,
deviceName:String,
devicePlace:String,
socket : [{number: Number,name:String, state : Boolean, current: Number, image:Number,locked:Boolean,reserved:Boolean}]
});
I already have a device in my database with four sockets.
Here example!
This is original data.
{
"_id" : ObjectId("5626569006bc3da468bafe93"),
"deviceId" : "0013A20040B5769A",
"deviceName" : "device",
"devicePlace" : "place",
"__v" : 0,
"socket" : [
{
"_id" : ObjectId("5628bd83570be84e28879e2d"),
"number" : 0,
"name" : "name"
"state" : true,
"current" : 0
"image" : 0,
"locked" : false,
"reserved" : false,
}, ...
]
}
and I received data from client for update.
{
"_id" : ObjectId("5626569006bc3da468bafe93"),
"deviceId" : "0013A20040B5769A",
"__v" : 0,
"socket" : [
{
"_id" : ObjectId("5628bd83570be84e28879e2d"),
"number" : 0,
"name" : "new name!!!!!"
"state" : true,
"current" : 0
}, ...
]
}
Now I'm trying to update a specific socket's name in the database with the following command:
device.update({deviceId: newData.deviceId, "socket.number": newData.number}, {$set: {"socket.$.name": newData.name}})
newData is object that extracted from socket array in received data.
I want to just update first socket's name.
or if possible, I want to update every socket's name as received socket array.
But this does not seem to be working, but I get no error. Can someone pin point what I'm doing wrong?

Aggregate mongodb records with self-defined time period

I have a Collection that contains some event reported by client, such as:
{ "_id" : ObjectId("54f43159c922ac0b4387ef9c"), "appversion" : "v1.2", "appid" : "930370913", "clkip" : "", "actip" : "", "clktime" : 1425289561, "acttime" : 0, "platform" : "google", "isnotified" : false, "idfa" : "14A900D9-A61A-41DC-A327-96EBE4BA57B31" }
{ "_id" : ObjectId("54f43159c922ac0b4387ef9d"), "appversion" : "v1.2", "appid" : "930370913", "clkip" : "", "actip" : "", "clktime" : 1425289561, "acttime" : 0, "platform" : "google", "isnotified" : false, "idfa" : "14A900D9-A61A-41DC-A327-96EBE4BA57B32" }
{ "_id" : ObjectId("54f43159c922ac0b4387ef9e"), "appversion" : "v1.2", "appid" : "930370913", "clkip" : "", "actip" : "", "clktime" : 1425289561, "acttime" : 0, "platform" : "facebook", "isnotified" : false, "idfa" : "14A900D9-A61A-41DC-A327-96EBE4BA57B33" }
{ "_id" : ObjectId("54f43159c922ac0b4387ef9f"), "appversion" : "v1.2", "appid" : "930370913", "clkip" : "", "actip" : "", "clktime" : 1425289561, "acttime" : 0, "platform" : "google", "isnotified" : false, "idfa" : "14A900D9-A61A-41DC-A327-96EBE4BA57B34" }
You can see that clktime is a unix timestamp (self defined, not the one Mongodb generated) with the precision of Second, I want to know how many events per 5 mins each paltform has reported(by clktime), I know I should use mongodb's Aggregate framework such as:
db.event.aggregate([{$match:{clktime:{$gt:1425204775}}},{$group:{_id:???, count:{$sum:1}}}])
^^^
I really don't know what this _id should be.
But I don't know how to define the _id of $group :-(
The output I want to achieve is like this:
{ "_id" : 0, "time":1425207775, "count" : 100 }
{ "_id" : 0, "time":1425210775, "count" : 51 }
{ "_id" : 0, "time":1425213775, "count" : 51 }
It will be nicer if the platform information could be identified too. But if it's too complex, You can give some reference and I will dig into it myself.
Any suggestion will be appreciate.
Not a problem really and not too hard. You just need "date math" to work with the "5 minute intervals" that you describe since this is a "number" and not a "date" value. It's still possible with "Date" objects ( which you should really be using because there is little to no overhead and not much difference in processing ) but let's stick to the point:
db.event.aggregate([
{ "$match": { "clktime":{ "$gt": 1425204775 } } },
{ "$group": {
"_id": {
"$subtract": [
"$clktime",
"$mod": [ "$clktime", 60 * 5 ] // 5 minutes in seconds
]
},
"count": { "$sum": 1 }
}}
])
Rounding out the values to 5 minute intervals gets the grouping data you want in the _id grouping key.
Also the _id value is the "grouping key", so your expected result is not valid and it can only be something that is "uniquely grouped" upon. This is not really any different to SQL "GROUP BY" if you are familiar with that.

Categories

Resources