Mongoose update array property - arrays

I am trying to update a document via Mongoose, but it does not update the array property.
Here's an example document:
{
"_id" : "55da477a9bfc910e38zzccf2",
"projectname" : "ASong",
"owner" : "adam",
"tracks" : [{
"name" : "Bass",
"file" : "upload/Bass.mp3",
"volume" : "0.75",
"pan" : "0.65"
}, {
"file" : "upload/Drums.mp3",
"volume" : "0.4",
"pan" : "-0.75",
"name" : "Drums"
}
],
"users" : ["adam", "eve"]
}
if I pass to Mongoose an object and try to use it to update like this:
var id = req.body._id;
var editedProject = req.body;
delete editedProject._id;
console.log("TRACKS: " +JSON.stringify(editedProject.tracks));
Project.update({"_id": id}, editedProject, {"upsert": true}, function(err, proj) {
if (err) {
res.send(err);
}
res.json(proj);
});
Only the 1st level properties are updated, but not the array.
I've found some solutions that involve looping through the array elements and calling an update for each element, but I would like to avoid that and keep the update as a single operation.
Or is it better to avoid using arrays?

Related

Rename a sub-document field within an Array of an Document

I am trying to rename the particular child field inside an array of an collection in MONGODB
{
"_id" : Id("248NSAJKH258"),
"isGoogled" : true,
"toCrawled" : true,
"result" : [
{
"resultsId" : 1,
"title" : "Text Data to be writen",
"googleRanking" : 1,
"isrelated" : false
},
{
"resultId" : 2,
"title" : "Text Data",
"googleRanking" : 2,
"isrelated" : true
}]
**I need to rename "isrelated" to "related" ** from the collection document
Using mongo Version 4.0
I Tried :
db.collection_name.update({}, { $rename: { 'result.isrelated': 'result.related'} } )
But it didn't worked in my case
As mentioned in official documentation $rename not working for arrays.
Please check link below:
https://docs.mongodb.com/manual/reference/operator/update/rename/
But you can do something like this
let newResult = [];
db.aa1.find({}).forEach(doc => {
for (let i in doc.result) {
newResult.push({
"resultsId" : doc.result[i]['resultsId'],
"title" : doc.result[i]['title'],
"googleRanking" : doc.result[i]['googleRanking'],
"related" : doc.result[i]['isrelated'],
})
}
db.aa1.updateOne({_id: doc._id}, {$set: {result: newResult}});
newResult = []
})

String from document meets value of array

I've got an array of Project ID's, for example:
[ 'ExneN3NdwmGPgRj5o', 'hXoRA7moQhqjwtaiY' ]
And in my Questions collection, I've got a field called 'project', which has a string of a project Id. For example:
{
"_id" : "XPRbFupkJPmrmvcin",
"question" : "Vraag 13",
"answer" : "photo",
"project" : "ExneN3NdwmGPgRj5o",
"datetime_from" : ISODate("2017-01-10T08:01:00Z"),
"datetime_till" : ISODate("2017-01-10T19:00:00Z"),
"createdAt" : ISODate("2017-01-10T08:41:39.950Z"),
"notificationSent" : true
}
{
"_id" : "EdFH6bo2xBPht5kYW",
"question" : "sdfadsfasdf",
"answer" : "text",
"project" : "hXoRA7moQhqjwtaiY",
"datetime_from" : ISODate("2017-01-11T11:00:00Z"),
"datetime_till" : ISODate("2017-01-11T17:00:00Z"),
"createdAt" : ISODate("2017-01-10T10:21:42.147Z"),
"notificationSent" : false
}
Now I want to return all documents of the Questions collection, where the Project (id) is one of the value's from the Array.
To test if it's working, I'm first trying to return one document.
Im console.logging like this:
Questions.findOne({project: { $eq: projectArray }})['_id'];
but have also tryed this:
Questions.findOne({project: { $in: [projectArray] }})['_id'];
But keep getting 'undefined'
Please try this.
Questions.find({project: { $in: projectArray }}) => for fetching all docs with those ids
Questions.findOne({project: { $in: projectArray }}) => if you want just one doc

MongoDB: Check for missing documents using a model tree structures with an array of ancestors

I'm using a model tree structures with an array of ancestors and I need to check if any document is missing.
{
"_id" : "GbxvxMdQ9rv8p6b8M",
"type" : "article",
"ancestors" : [ ]
}
{
"_id" : "mtmTBW8nA4YoCevf4",
"parent" : "GbxvxMdQ9rv8p6b8M",
"ancestors" : [
"GbxvxMdQ9rv8p6b8M"
]
}
{
"_id" : "J5Dg4fB5Kmdbi8mwj",
"parent" : "mtmTBW8nA4YoCevf4",
"ancestors" : [
"GbxvxMdQ9rv8p6b8M",
"mtmTBW8nA4YoCevf4"
]
}
{
"_id" : "tYmH8fQeTLpe4wxi7",
"refType" : "reference",
"parent" : "J5Dg4fB5Kmdbi8mwj",
"ancestors" : [
"GbxvxMdQ9rv8p6b8M",
"mtmTBW8nA4YoCevf4",
"J5Dg4fB5Kmdbi8mwj"
]
}
My attempt would be to check each ancestors id if it is existing. If this fails, this document is missing and the data structure is corrupted.
let ancestors;
Collection.find().forEach(r => {
if (r.ancestors) {
r.ancestors.forEach(a => {
if (!Collection.findOne(a))
missing.push(r._id);
});
}
});
But doing it like this will need MANY db calls. Is it possible to optimize this?
Maybe I could get an array with all unique ancestor ids first and check if these documents are existing within one db call??
First take out all distinct ancesstors from your collections.
var allAncesstorIds = db.<collectionName>.distinct("ancestors");
Then check if any of the ancesstor IDs are not in the collection.
var cursor = db.<collectionName>.find({_id : {$nin : allAncesstorIds}}, {_id : 1})
Iterate the cursor and insert all missing docs in a collection.
cursor.forEach(function (missingDocId) {
db.missing.insert(missingDocId);
});

How to query a single embedded document in an array in MongoDB?

I am trying to query a single embedded document in an array in MongoDB. I don't know what I am doing wrong. Programmatically, I will query this document and insert new embedded documents into the currently empty trips arrays.
{
"_id" : ObjectId("564b3300953d9d51429163c3"),
"agency_key" : "DDOT",
"routes" : [
{
"route_id" : "6165",
"route_type" : "3",
"trips" : [ ]
},
{
"route_id" : "6170",
"route_type" : "3",
"trips" : [ ]
},
...
]
}
Following queries -I run in mongo shell- return empty:
db.tm_routes.find( { routes : {$elemMatch: { route_id:6165 } } } ).pretty();
db.tm_routes.find( { routes : {$elemMatch: { route_id:6165,route_type:3 } } } ).pretty();
db.tm_routes.find({'routes.route_id':6165}).pretty()
also db.tm_routes.find({'routes.route_id':6165}).count() is 0.
The following query returns every document in the array
db.tm_routes.find({'routes.route_id':'6165'}).pretty();
{
"_id" : ObjectId("564b3300953d9d51429163c3"),
"agency_key" : "DDOT",
"routes" : [
{
"route_id" : "6165",
"route_type" : "3",
"trips" : [ ]
},
{
"route_id" : "6170",
"route_type" : "3",
"trips" : [ ]
},
...
]}
but db.tm_routes.find({'routes.route_id':'6165'}).count() returns 1.
And finally, here is how I inserted data in the first place -in Node.JS-:
async.waterfall([
...
//RETRIEVE ALL ROUTEIDS FOR EVERY AGENCY
function(agencyKeys, callback) {
var routeIds = [];
var routesArr = [];
var routes = db.collection('routes');
//CALL GETROUTES FUNCTION FOR EVERY AGENCY
async.map(agencyKeys, getRoutes, function(err, results){
if (err) throw err;
else {
callback(null, results);
}
});
//GET ROUTE IDS
function getRoutes(agencyKey, callback){
var cursor = routes.find({agency_key:agencyKey});
cursor.toArray(function(err, docs){
if(err) throw err;
for(i in docs){
routeIds.push(docs[i].route_id);
var routeObj = {
route_id:docs[i].route_id,
route_type:docs[i].route_type,
trips:[]
};
routesArr.push(routeObj);
/* I TRIED 3 DIFFERENT WAYS TO PUSH DATA
//1->
collection.update({agency_key:agencyKey}, {$push:{"routes":{
'route_id':docs[i].route_id,
'route_type':docs[i].route_type,
'trips':[]
}}});
//2->
collection.update({agency_key:agencyKey}, {$push:{"routes":routeObj}});
*/
}
// 3->
collection.update({agency_key:agencyKey}, {$push:{routes:{$each:routesArr}}});
callback(null, routeIds);
});
};
},
...
var collection = newCollection(db, 'tm_routes',[]);
function newCollection(db, name, options){
var collection = db.collection(name);
if (collection){
collection.drop();
}
db.createCollection(name, options);
return db.collection(name);
}
Note: I am not using Mongoose and don't want to use if possible.
Melis,
I see what you are asking for, and what you need is help understanding how things are stored in mongodb. Things to understand:
A document is the basic unit of data for MongoDB and can be roughly compared to a row in a relational database.
A collection can be thought of as a table with a dynamic schema
So documents are stored in collections.Every document has a special _id, that is unique within a collection. What you showed us above in the following format is One document.
{
"_id" : ObjectId("564b3300953d9d51429163c3"),
"agency_key" : "DDOT",
"routes" : [
{
"route_id" : "6165",
"route_type" : "3",
"trips" : [ ]
},
{
"route_id" : "6170",
"route_type" : "3",
"trips" : [ ]
},
...
]}
If you run a query in your tm_routes collection. The find() will return each document in the collection that matches that query. Therefore when you run the query db.tm_routes.find({'routes.route_id':'6165'}).pretty(); it is returning the entire document that matches the query. Therefore this statement is wrong:
The following query returns every document in the array
If you need to find a specific route in that document, and only return that route, depending on your use, because its an array, you may have to use the $-Positional Operator or the aggregation framework.
For Node and Mongodb users using Mongoose, this is one of the ways to write the query to the above problem:
db.tm_routes.updateOne(
{
routes: {
$elemMatch: {
route_id: 6165 (or if its in a route path then **6165** could be replaced by **req.params.routeid**
}
}
},
{
$push: {
"routes.$.trips":{
//the content you want to push into the trips array goes here
}
}
}
)

Pushing Data To A Child Node with AngularJS and Firebase

I'm getting this:
"users" : {
"simplelogin:129" : {
"-JbX-CJuMDf1H8-yCETV" : {
"gold" : {
"receive" : {
"amount" : 1,
"date" : 1416835946409,
"email" : "you#me.com"
}
}
},
But I need something like this:
"users" : {
"simplelogin:130" : {
"date" : 1416834728422,
"email" : "yam#dam.com",
"id" : "130",
"gold" : {
"receive" : {
"-JbWva7Gh9Y3RarlF77h" : {
"amount" : 1,
"date" : 1416834737201,
"email" : "you#do.com"
},
If I use .update instead of .push, I get the file structure I need, but then it overrides it for each transaction instead of adding a new one each time.
receive.orderByChild("email").equalTo( $scope.user.email ).once('child_added', function(snap) {
snap.ref().push({gold: {receive: myGold}}).then(function() {
});
Your question is not very clear, but I assume that you want to push the new node deeper in the tree.
simplelogin:130
date: ...
email: "yam#dam.com"
id: 130
gold
received
-JbX-CJuMDf1H8-yCETV
amount: 1
date: ...
email: "yam#dam.com"
To put the data into gold/received, you'd do:
snap.ref().child('gold/receive').push(myGold);
So you first find the node you want to add something to and only then call push to add a new child (with a new unique id) there.

Resources