ng-repeat showing functions names and data - mongodb

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);
};

Related

Get data according _id

I try to query MongoDB inside nodejs to get data for _id x I use
async function getTestData(id){
return new Promise((resolve, reject) => {
MongoClient.connect(uri, { useNewUrlParser: true, keepAlive: 1 }, function(err, client) {
const dbo = client.db("test");
var query = { _id: id };
dbo
.collection("smscripts")
.find(query)
.project({ 'data' : 1})
.toArray(function(err, items) {
err
? reject(err)
: resolve(items);
});
});
});
}
Query is
{ _id: '5dada7dfdca94dbaf65d9547' }
But I always get back an empty array. Anybody can help me out why the array is always empty? By the way, err is null. The id definitely exists.
in mongo db _id are prefix with ObjectId
so you need value first try this
id = ObjectId("507c7f79bcf86cd7994f6c0e")
and then compare it to ID.
hope it helps
First You need to import..
import { ObjectId } from "bson"
Then in Your code " var query = { _id: id }; " replace it with this..
var query = { '_id' : ObjectId(id) }
Then, in your code you are using .toArray() method. this would takes more time to
convert result to array. so you need to use await keyword before moving on.
Using Async-Await pattern this is very simple ..
const client = await MongoClient.connect(uri, { useNewUrlParser: true, keepAlive: 1 })
.catch(err => { console.log(err); });
if (!client) return;
try {
const dbo = client.db('test');
let collection = dbo.collection('smscripts');
let query = { '_id' : ObjectId(id) };
let projection = { 'data' : 1 } ;
let cursor = await collection.find(query, projection).toArray();
console.log(cursor);
return cursor;
} catch (err) {
console.log(err);
} finally {
client.close();
}
hope this works for you.

Mongodb: db undefined on connect

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"
});

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;
}
})

Sequelize - Cannot save associations in 1:N relationship

What you are doing?
trying to add associations and save them to database
js
var Device = models.Device;
var Log = models.Log;;
var logs = [
{
"message_level" : 1,
"message" : "test log 1"
},
{
"message_level" : 1,
"message" : "test log 2"
},
{
"message_level" : 1,
"message" : "test log 3"
}
];
var devID = 'X3dE4DEW';
describe('Logs', function() {
it('should create log', function(done) {
Device.create({
"originalID" : devID
}).then(
function() {
return Device.findOne({"where": {originalID: devID},
include: [ { model: Log, as : "Logs" } ] }).then(
function(device) {
if (device) {
logs = logs.map(
function(log) {
return Log.build(log);
}
);
console.log(logs) // is NOT Empty -> OK
return device.addLogs(logs).then(
function(device) {
return device.getLogs().then(
function(logs) {
console.log(logs); // EMPTY [] -> NOT OK
logs.length.should.equal(3);
done();
}
);
}
);
}
return Promise.reject('Not valid Device ID');
}
).catch(function(error){
console.log(error);
done();
});
}
);
});
});
here is how are they defined
// models
// Device
Device = pg.define('device', {
originalID: {
type: Sequelize.STRING(16) // Up to 16
}
});
// LogRecord
Log = pg.define('log', {
message_level: {
type: Sequelize.INTEGER
},
message: {
type: Sequelize.STRING(100) // Up to 100
}
});
Device.hasMany(Log, { as : "Logs" });
Log.belongsTo(Device);
What do you expect to happen?
addLogs should save associations items to the database
What is actually happening?
Items are not saved, device.getLogs() is returning an empty array []
{ AssertionError: expected 0 to equal 3 }
Dialect: PG
Database version: 9.6.1
Sequelize version: ~3.30.x
There's several solutions to associate rows
if you're using add<Association(s)> function, be sure that associated objects are already stored in database.
or you can use create<Association> to create model and associate.
var device;
Device.create({
"originalID" : devID
}).then(function(createdDevice) {
device = createdDevice;
return Promise.all(logs.map(log=>{return device.createLog(log);}));
}).then(function(result) {
return device.getLogs();
}).then(function(logs) {
console.log(logs);
logs.length.should.equal(3);
done();
}).catch(function(error){
console.log(error);
done();
});
Use promises style like above, it's more understandable, not "go deep into promises".

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);
}
);