Mongodb: db undefined on connect - mongodb

I am trying to access mongodb through native driver.
When i use connect method in my remote method. I am getting connected successfully but i am getting "undefined" as db object
Purpose : Getting all fields name from collection.
Activation.getUserFields = function (id, callbackFn) {
Activation.app.dataSources.mongoConnector.connect(function (errconnect, mdb) {
if (errconnect) callbackFn(errconnect, {});
else {
console.log('mdb', mdb);
var mr = mdb.runCommand({
"mapreduce": "Visit",
"map": function () {
for (var key in this) { emit(key, null); }
},
"reduce": function (key, stuff) { return null; },
"out": "Visit" + "_keys"
});
mdb[mr.result].distinct("_id").toArray(function (errFields, docFields) {
if (errFields) callbackFn(errFields, {});
else {
callbackFn(null, docFields);
}
});
}
});
};
};
What am i missing here?

In LoopBack You can access Model and Collection by :
Plz try :
const ActivationCollection = Activation.getDataSource().connector.collection("Activation");
ActivationCollection.runCommand({
"mapreduce": "Visit",
"map": function () {
for (var key in this) { emit(key, null); }
},
"reduce": function (key, stuff) { return null; },
"out": "Visit" + "_keys"
});

Related

MongoDB putting they key into $set instead of using it for lookup?

I am trying to update a message using userID as my _id
Is splitting it up into findOne - Save - Update the best way?
//
// Find and update message
//
var messageModel = require('../models/messageModel');
var messageTable = mongoose.model('messageModel');
var messageRecord = new messageModel();
var findMessage = () => {
return new Promise((resolve, reject) => {
console.log("=====START findMessage=====")
messageTable.findOne(
{ _id: userID }
,function(err, data) {
if (err) {
reject(new Error('findMessage: ' + err))
return;
}
// Who will have this as unread?
if (userManager==true) {
messageRecord.readUser = false;
messageRecord.readManager = true;
} else {
messageRecord.readUser = true;
messageRecord.readManager = false;
}
// If message not found, then create new one
if (!data) {
console.log("=====CREATE NEW RECORD=====")
messageRecord._id = userID;
messageRecord.activityDate = Math.round(new Date().getTime()/1000);
messageRecord.messages = {
"message" : message,
"date" : Math.round(new Date().getTime()/1000),
"property" : propertyID,
"booking" : bookingID,
"manager" : userManager
}
messageRecord.save(function (err, res) {
if (err) {
reject(new Error('findMessage: ' + err));
return;
}
})
console.log("=====RESOLVE findMessage=====")
resolve();
return;
}
// If message found, then add message
console.log("=====ADD LINE TO RECORD=====")
messageTable.update (
{ _id: userID },
{
$set: {
activityDate : Math.round(new Date().getTime()/1000),
readUser : messageRecord.readUser,
readManager : messageRecord.readManager
},
$push: {
messages: {
"message" : message,
"date" : Math.round(new Date().getTime()/1000),
"property" : propertyID,
"booking" : bookingID,
"manager" : userManager
}
}
},
{ upsert: true }
).exec(function (err, res) {
if (err) {
reject(new Error('findMessage: ' + err));
return;
}
})
console.log("=====RESOLVE findMessage=====")
resolve();
return;
});
})};
Do I need to put upsert:true? (what ever that means)
Or should I use findOneAndUpdate?
And would you use findOneAndUpdate or just update? And why?
I tought it went like this:
findone
if not found then save
if found then update
UPDATE - Thanks to lascot I ended up doing this, and it works great!
// Save message
messageTable.update (
{ _id: userID },
{
$setOnInsert: {
_id: userID
},
$set: {
activityDate : Math.round(new Date().getTime()/1000),
readUser : messageRecord.readUser,
readManager : messageRecord.readManager
},
$push: {
messages: {
"message" : message,
"date" : Math.round(new Date().getTime()/1000),
"property" : propertyID,
"booking" : bookingID,
"manager" : userManager
}
}
},
{ upsert: true }
).exec(function (err, res) {
if (err) {
reject(new Error('findMessage: ' + err));
return;
}
})

Mongoose update array of Object id's using Populate?

I am trying to populate my array of an object id's how can i do ??
Function
$scope.assignEmployees = function () {
var chkArray = [];
var companyName = $scope.selectedComapny.companyName;
var Indata = {chkvalue:chkArray,company_name:companyName};
$("#employee_name:checked").each(function() {
chkArray.push($(this).val());
});
$http({
method : 'PUT',
url : '/api/projects',
data : Indata
})
.success(function (data){
console.log(data);
});}
Mongoose api
Population code:-
Project.findOne({client : company_name})
.populate('assignedTo')
.exec(function(err, project) {
if (err) return;
while(i<employee_id.length){
project.assignedTo.push(employee_id[i]);
project.save(function(err) {
if (err) return;
})
i++;
}
});
This code is work but it insert value 4 times any idea guys.
You can use this code to push all elements of Array to an Array in mongoose.
Project.update(
{ client: company_name },
{ "$pushAll": { "assignedTo": employee_id } },
function (err, raw) {
if (err) return handleError(err);
console.log('The raw response from Mongo was ', raw);
}
);

Mongodb find and insert

I would like to:
1) find documents
2) each of the found documents include an array, I would like to insert a new array element into the array. If the array element already exists, do nothing (do not insert a new element into the array).
I've played with aggregation however I can't seem to find an insert function?
Data:
{
"_id" : ObjectId("560c24b853b558856ef193a4"),
"name" : "ирина",
"pic" : "",
"language" : ObjectId("560c24b853b558856ef193a2"),
"cell" : 1,
"local" : {
"email" : "ирина#mail.com",
"password" : "12345"
},
"sessions" : [ // <--- this is the array I would like to insert a new element into
{
"id" : ObjectId("560c24b853b558856ef193a5")
}
]
}
Insert:
yield new Promise(function (resolve, reject) {
users.col.aggregate([
{
$match: {
'cell': socket.cell
}
},
{
// <--- insert here?
}
],
function (err, res) {
if (err === null)
resolve(res);
reject(err);
});
});
Update.
Tried the following also not willing to insert :/
yield new Promise(function (resolve, reject) {
var bulk = users.col.initializeUnorderedBulkOp();
bulk.find({
cell: 1
}).update({
$addToSet: {
sessions: {
id: 'test'
}
}
});
bulk.execute(function (err, res) {
console.log(res);
resolve(res);
});
});
As stated by user3100115 you should use update as follows:
db.collection.update({cell:1},{$addToSet:{sessions:{id: 'test'}}},{multi:true})
Using co-monk:
yield users.update({
cell: 1
}, {
$addToSet: {
sessions: {
id: 'test'
}
}
}, {
multi: true
});
You can use Bulk operations, particularly Bulk.find and update. As for adding unique values, you can use $addToSet
var bulk = db.items.initializeUnorderedBulkOp();
bulk.find({cell: socket.cell}).update({$addToSet: {sessions: id}});

How to use aggregrate in mongodb to $match _id

Document:
{
"_id" : ObjectId("560c24b853b558856ef193a3"),
"name" : "Karl Morrison",
"pic" : "",
"language" : ObjectId("560c24b853b558856ef193a2"),
"cell" : 1,
"local" : {
"email" : "karl.morrison#instanty.se",
"password" : "12345"
},
"sessions" : [
{
"id" : ObjectId("560c24b853b558856ef193a5")
}
]
}
This works:
yield new Promise(function (resolve, reject) {
users.col.aggregate([
{
$match: {
'name': 'Karl Morrison'
}
}
],
function (err, res) {
console.log('err ' + err);
console.log('res ' + JSON.stringify(res)); // <-- echos the object retrieved
if (err === null)
resolve(res);
reject(err);
});
});
This does not work:
yield new Promise(function (resolve, reject) {
users.col.aggregate([
{
$match: {
'_id': '560c24b853b558856ef193a3' // <-- _id of the user
}
}
],
function (err, res) {
console.log('err ' + err);
console.log('res ' + JSON.stringify(res));
if (err === null)
resolve(res);
reject(err);
});
});
The .col access the native mongodb object (using co-monk otherwise). So I'm doing it manually. This however isn't working. I suspect I am not casting the id hexstring to an ObjectId. No matter what I try nothing works.
const ObjectId = mongoose.Types.ObjectId;
const User = mongoose.model('User')
User.aggregate([
{
$match: { _id: ObjectId('560c24b853b558856ef193a3') }
}
])
Try this
const User = require('User')
const mongoose = require("mongoose");
User.aggregate([
{
$match: { _id: new mongoose.Types.ObjectId('560c24b853b558856ef193a3') }
}
])
use toString() method
const User = mongoose.model('User')
User.aggregate([
{
$match: { _id: user_id.toString() }
}
]

ng-repeat showing functions names and data

I'm a beginner with angularjs and mongolab ..
I have this code, to edit a record in mongolab :
function EditCtrl($scope, $location, $routeParams, Project) {
var self = this;
Project.get({id: $routeParams.projetId}, function(projet) {
self.original = projet;
$scope.projet = new Project(self.original);
});
$scope.save = function() {
$scope.projet.update(function() {
$location.path('/list');
});
};
}
It works perfectly.
I wanted to display all the keys and values from the record, this is the code :
<div ng-repeat="(key, val) in projet">
<div>{{key}}:{{val}}</div>
</div>
And this is the result :
_id:{}
destroy:
name:Test test
rang:4
update:
In my record, i only have the _id, name and rang. I don't know why "destroy:" dans "update:" are displayed! probably because i use this code to connect to mongolab :
angular.module('mongolab', ['ngResource']).
factory('Project', function($resource) {
var Project = $resource('https://api.mongolab.com/api/1/databases' +
'/_____/collections/_________/:id',
{apiKey: '___________________'}, {
update: {method: 'PUT'}
}
);
Project.prototype.update = function(cb) {
return Project.update({id: this._id.$oid},
angular.extend({}, this, {_id: undefined}), cb);
};
Project.prototype.destroy = function(cb) {
return Project.remove({id: this._id.$oid}, cb);
};
return Project;
});
What should i do to only display the record data ?
thanks
Return a service and pass the item you receive from get() back to update and destroy.
factory('Project', function($resource) {
return {
get: function() {
return $resource('https://api.mongolab.com/api/1/databases' +
'/_____/collections/_________/:id',
{apiKey: '___________________'}, {
update: {method: 'PUT'}
},
update : function(itm, cb) {
return item.update({id: item._id.$oid},
angular.extend({}, item, {_id: undefined}), cb);
},
destroy : function(item, cb) {
return item.remove({id: item._id.$oid}, cb);
};
Otherwise you can instantiate only one and reference it
factory('Project', function($resource) {
var item =$resource('https://api.mongolab.com/api/1/databases' +
'/_____/collections/_________/:id',
{apiKey: '___________________'}, {
update: {method: 'PUT'}
return {
update : function(cb) {
return item.update({id: item._id.$oid},
angular.extend({}, item, {_id: undefined}), cb);
},
destroy : function(cb) {
return item.remove({id: item._id.$oid}, cb);
};