How to update collection in init.js using Mongo script? - javascript

I have the following collection
users
{
"_id" : ObjectId("..."),
"username" : "admin",
"permissions" : {
"keycloakId" : "...",
"roles" : [
"admin"
]
},
}
I need to update roles field. I want to assign new role to every user. How can I iterate over collection using mongo script which I am gonna put to docker-entrypoint-initdb.d / init.js?
Here is my code
db.getCollection('users').find({}).forEach(
function (elem) {
elem.update({
_id: elem._id
}, {
$set: {
permissions.roles: ['newRole']
}
}
);
}
)
I got this error:
2022-12-01T09:51:17.394+0000 E QUERY [js] uncaught exception: SyntaxError: missing : after property id :
#(shell):9:30
2022-12-01T09:51:17.395+0000 E QUERY [js] uncaught exception: SyntaxError: expected expression, got '}' :

Related

MongoDB unset removes everything in child

I have a db structure like this:
{ "_id" : ObjectId("5fd48e12e5e0fd174c1a7260"),
"races" : {
"example1" : { "date" : "12/18/2020", "status" : "pending" },
"example2" : { "date" : "12/18/2020", "status" : "domestic" }
}
and I am attempting to just remove example 1 by using the following block of code(javascript):
self.db = client.db("authinfo");
self.collection = self.db.collection("users");
this.delete_both_races = function (user1) {
self.collection.updateOne({user:user1} ,{$unset:{races:"example1"}} ,function(error,result){});
same thing happens when running the following command in the mongo.exe command line program:
db.users.updateOne({user:"anything"} , {$unset:{races:"example1"}})
I get the result of(remaining elements after unsetting) :
{ "_id" : ObjectId("5fd48e12e5e0fd174c1a7260") }
desired result :
{ "_id" : ObjectId("5fd48e12e5e0fd174c1a7260"),
"races" : {
"example2" : { "date" : "12/18/2020", "status" : "domestic" }
}
You should unset races.example1 instead of races.
From MongoDB document,
The specified value in the $unset expression (i.e. "") does not impact the operation.
To specify a in an embedded document or in an array, use dot notation.
Mongo Playground

Sequelize Syntax Error (N\')

I'm trying a like query in name & surname columns with a dynamic input, using ES6 string interpolation.
This is my code:
User.findAll({
where: {
[Op.or] : [
{
nombre: {
[Op.iLike] : `%${name}%`
}
},
{
apellido: {
[Op.iLike] : `%${name}%`
}
}
]
},
attributes:userAttr,
})
Sequelize adds automatically N\' at beginning in each dynamic variable, and throws the following SQL statement:
'SELECT [id] AS [id], [mail] AS [email], [nombre] AS [name], [apellido] AS [surname], [nro_celular] AS [cellphone], [tipo] AS [type], [id_usuario_estado_actual] AS [userCurrentStatusID], [push_token] AS [pushToken], [push_user_id] AS [pushUserID], [documento] AS [document], [tipo_documento] AS [documentType], [fecha_creacion] AS [creationDate], [id_ciudad] AS [cityID], [id_empresa] AS [companyID], [default_payment] AS [paymentDefault] FROM [dbo].[usuario] AS [user] WHERE ([user].[nombre] ILIKE N\'%Axel Candia%\' OR [user].[apellido] ILIKE N\'%Axel Candia%\');'
Which throws the following error
UnhandledPromiseRejectionWarning: SequelizeDatabaseError: Incorrect syntax near 'ILIKE'.
I've tried the following suggestions, unsuccessfully:
[Op.iLike] : '%'+name+'%'
$iLike : '%'+name+'%'
[Op.iLike] : ['%'+name+'%']
Any other suggestion?
SOLVED 6/28/2018 11:03 AM
The error wasn't focused in N\' added by Sequelize,
[Op.iLike] it's only for PG (Postgres) Database, not mine (SQL Server).
Instead, [Op.like] works as charm! However, I should code a solution for insensitive case in dynamic variables.

How I can get ID of a new record in mongoDB?

There is such a document structure in MongoDB
{
"_id" : ObjectId("58f7d556aa52ce456672a67e"),
"created" : ISODate("2017-04-19T21:23:34.315Z"),
"context_task" : [
{
"task" : "some text ",
"status" : false,
"_id" : ObjectId("58f7d559aa52ce456672a67f")
}
],
"head" : {
"userID" : "58f48037fc894e19a3f7b81b",
"head_task" : "test record "
},
"__v" : 0
}
I add data to the context_task.task using the following query:
task.findOneAndUpdate({"_id": req.body.id_project},
{$push: {'context_task': {'task': req.body.input_task,'status': false}}},{new: true},
function (err, doc) {
if (err) return next(err);
var body = req.body.id_project+","+req.body.input_task;
console.log(doc);
res.status(200).send(body);
});
Tell me, how can I get the context_task._id of a new record after inserting it? In this case, the entire document is returned.
Every mongo document is associated with a default _id, in case not provided it will be ObjectId.
In case you want to use _id value for any other purpose, why don't you have your own _id value, which has to be unique throughout collection. The value can be of any datatype as well as nested also.

Can't get data from MongoDB database for web app

I'm new to using MongoDB. Currently, I am making a web application that requires some data storage. I established an HTTP server on Node.js that runs on localhost:3000. I also built a virtual development environment using Vagrant and VirtualBox. I am accessing the Mongo shell from PuTTy (if that is relevant at all). Before incorporating MongoDB, it worked fine as I was storing the data in the Node.js program memory.
This web app is an online to-do-list. The first error that I am getting is with the get route. The list of "to-do"s that I have inserted into the Mongo database would not appear on the site in localhost. It seems to not be getting the data from the database. The second error that I am getting is with the post route. When I insert a "to-do" through the user interface at localhost and I refresh the page, the to-do-list on localhost gets updated with that particular to-do (but not with the ones I inserted in the database). But, it doesn't seem to add it into the database, and I still get this error on the console:
vagrant#precise32:~/app$ node server.js
{ description: 'descTest3', tags: [ 'tagTest3' ] }
Mongoose: mpromise (mongoose's default promise library) is deprecated, plug in your own promise library instead: http://mongoosejs.com/docs/promises.html
I'm not sure why I got that error since I do not seem to be using any promises.
server.js
var express = require("express"), http = require("http"), app = express(), mongoose = require("mongoose");
app.use(express.static(__dirname + "/client"));
app.use(express.urlencoded());
mongoose.connect('mongodb://localhost/WatNext');//connect to the WatNext data store in mongoDB
var ToDoSchema = mongoose.Schema({
"description": String,
"tags": [ String ] //array of Strings
});
var ToDo = mongoose.model("ToDo", ToDoSchema)
http.createServer(app).listen(3000);
//get and post routes:
app.get("/toDos.json", function (req, res) {
ToDo.find({}, function (err, toDos) {
if (err != null){
console.log(err);
}
res.json(toDos);
});
});
app.post("/todos", function (req, res) {
console.log(req.body);
var addedToDo = new ToDo({"description" : req.body.description, "tags" : req.body.tags});
//save function saves object into the database
addedToDo.save(function (err, result) {
if (err != null){//if there is an error
console.log(err);
res.send("ERROR SAVING");
}
else {
ToDo.find({}, function (err, result) {
if (err != null){//if there is an error in finding
res.send("ERROR FINDING");
}
res.json(result);
});
}
});
});
app.js
var main = function (toDoObjects) {
//do stuff with ToDoObjects including outputting the list of ToDos
};
$(document).ready(function() {
$.getJSON("toDos.json", function(toDoObjects) {
main(toDoObjects);
})
});
mongo shell
> show dbs
WatNext 0.0625GB
local 0.03125GB
> use WatNext
switched to db WatNext
> show collections;
system.indexes
toDoCollection
todos
> db.toDoCollection.find();
{ "_id" : ObjectId("58b38dd8fb355f57162d9cf1"), "description" : "Get groceries and eat afterwards", "tags" : [ "shopping", "chores" ] }
{ "_id" : ObjectId("58b38dd8fb355f57162d9cf2"), "description" : "Make up some new To-Dos", "tags" : [ "writing", "work" ] }
{ "_id" : ObjectId("58b38dd8fb355f57162d9cf3"), "description" : "Prep for Monday's class", "tags" : [ "work", "teaching" ] }
{ "_id" : ObjectId("58b38dd8fb355f57162d9cf4"), "description" : "Answer emails", "tags" : [ "work" ] }
{ "_id" : ObjectId("58b38dd8fb355f57162d9cf5"), "description" : "Take April to the park", "tags" : [ "chores", "pets" ] }
{ "_id" : ObjectId("58b38dd8fb355f57162d9cf6"), "description" : "Finish writing this book", "tags" : [ "writing", "work" ] }
EDIT:
I found out it was just an error of naming.
I also found out that
mongoose.Promise = require("bluebird");
solved the problem with the promise error. Remember to install the module first though:
npm install --save bluebird
I found out what was wrong. It was an error in naming for the GET and POST routes. It should have been:
app.get("/todos.json", function (req, res) { //get the data from the collection called 'todos' in MongoDB
as well as:
$.getJSON("todos.json", function(toDoObjects) {
I should have used the todos collection instead of toDoCollection:
"description" : "descTest1", "_id" : ObjectId("58b39a1fb1a30305075408fa"), "tags" : [ "tagTest2" ], "__v" : 0 }
{ "description" : "descTest2", "_id" : ObjectId("58b4c837d47a5604c7c0609a"), "tags" : [ "tagsTest2" ], "__v" : 0 }
{ "description" : "descTest3", "_id" : ObjectId("58b4ca0491f4c804d200cda9"), "tags" : [ "tagTest3" ], "__v" : 0 }
{ "description" : "descTest4", "_id" : ObjectId("58b4e636b71d0a05ebb7a71a"), "tags" : [ "tagTest4" ], "__v" : 0 }
{ "description" : "descTest5", "_id" : ObjectId("58b60211428520053a4714ed"), "tags" : [ "tagTest5" ], "__v" : 0 }
{ "_id" : ObjectId("58b6037839e65d96e13cf68e"), "description" : "descTestMONGO", "tags" : [ "tagTestMONGO" ] }
{ "_id" : ObjectId("58b605b339e65d96e13cf690"), "description" : "Take April to the park", "tags" : [ "chores", "pets" ] }

Angular / Meteor: Array is undefined

I'm building an Angular / Meteor application, using Meteor's reactivity to populated an Angular model. It is all working fine until I start working with arrays.
// get sentence
$scope.sentence = $meteor.object(Sentences, $stateParams.sentenceId);
// related sentences
$scope.relatedSentences = $meteor.collection(function() {
return Sentences.find({_id: { $in: $scope.sentence.relatedSentences }});
});
I get this error on the JavaScript console
Error: $in needs an array
at Error (native)
at Object.ELEMENT_OPERATORS.$in.compileElementSelector (http://localhost:3000/packages/minimongo.js?af9eb9d7447544ca9b839a3dcf7ed2da2209b56c:1894:15)
at http://localhost:3000/packages/minimongo.js?af9eb9d7447544ca9b839a3dcf7ed2da2209b56c:1576:19
at Function._.each._.forEach (http://localhost:3000/packages/underscore.js? 0a80a8623e1b40b5df5a05582f288ddd586eaa18:164:22)
In the Mongo / Meteor console
meteor:PRIMARY> db.sentences.find({_id: "sp75iWPNqpbp2ypmy"});
{ "_id" : "sp75iWPNqpbp2ypmy", "sentence" : "Here is sentence 1 ", "language" : "en", "level" : "A1", "public" : true, "relatedSentences" : [ "wNs4ByDq7t396WLM3" ] }
And
meteor:PRIMARY> db.sentences.find({_id: { $in: [ "wNs4ByDq7t396WLM3" ] }});
{ "_id" : "wNs4ByDq7t396WLM3", "sentence" : "Here is sentence 0 ", "language" : "en", "level" : "A1", "public" : true, "relatedSentences" : [ ] }
I then commented out the failing find and have outputted the objects to html
$scope.sentence = $meteor.object(Sentences, $stateParams.sentenceId);
$scope.test = typeof $scope.sentence.relatedSentences;
Sentence: {{sentence}}<br/>
Related: {{sentence.relatedSentences}}<br/>
Typeof: {{test}}
Results
Sentence: {"autorunComputation": {"stopped":false,"invalidated":false,"firstRun":false,"_id":47,"_onInvalidateCallbacks": [null,null],"_parent":null,"_recomputing":false},"_id":"oFMp7swYyQsXkYsKz","sent ence":"Here is sentence 2","language":"en","level":"A1","public":true,"relatedSentences": ["wNs4ByDq7t396WLM3"]}
Related: ["wNs4ByDq7t396WLM3"]
Typeof: undefined
The Array is marked as undefined, but it is clearly shown in the full object. What am I missing?
EDIT
When running the above test on Firefox it returns an object
Related: ["wNs4ByDq7t396WLM3"]
Typeof: object
Related issue
$scope.test is only bound one time when this code initially runs. There is no data binding, so even if $scope.sentence.relatedSentences changes, test will not. The issue is that $scope.sentence.relatedSentences is populated asynchronously.
This would also apply to $scope.relatedSentences -- you are trying to set it initially before $scope.sentence.relatedSentences is available. You can use .subscribe on the value returned from .object to set this once the data is available.
$scope.sentence.subscribe().then(function () {
$scope.relatedSentences = $meteor.collection(function() {
return Sentences.find({_id: { $in: $scope.sentence.relatedSentences }});
});
});

Categories

Resources