Get Error when Insert to Mongo collection - javascript

I have two collection that contains:
"DeviceId" : "",
"FirstName" : "",
"LastName" : "",
"AllowDomains" : "",
"JobLocationName" : ""
and so on. I write this query that first check that deviceId in collection1 is the same of deviceId in collection2. If were same then do nothing otherwise must copy into temp Collection.
but first:
It does not compare at all and these code copy all documents?
and second, middle of copy process I got error?
function compareCollection (dv, F2){
var compare = F2.find().forEach(function(doc1){
if (doc1.DeviceId === dv ) {
return false;
} else {
insertToColl(doc1.DeviceId)
}
});
}
var result;
db.getCollection('FinalLocation').find({}, {DeviceId: 1}).forEach(function(u)
{
result = u.DeviceId;
});
compareCollection(result , db.getCollection('FinalLocation_'));
function insertToColl(info){
var post = {
"DeviceId" : info,
"FirstName" : "",
"LastName" : "",
"AllowDomains" : "",
"JobLocationName" : ""
};
db.getCollection('tempColl').save([post], function (err, result) {
if (err) {
console.log("ERROR ", err);
}
else {
console.log("SUCCESS INSERTED in to users collection _is are ", result.length, result)
}
});
}
these error appear when mongo want's insert data into collection:
2017-09-26T15:41:47.467+0330 E QUERY [thread1] Error: can't save a number or string :
DBCollection.prototype.save#src/mongo/shell/collection.js:615:1
insertToColl#(shell):2:3
compareCollection/compare<#(shell):7:7
DBQuery.prototype.forEach#src/mongo/shell/query.js:501:1
compareCollection#(shell):2:17
#(shell):1:1

Related

Using Firebase, how can I create a query based on UID?

I created a function that adds a UID to the database along with an item's state:
changestate(item) {
var postData = {
state: "listed",
};
var user = firebase.auth().currentUser;
var uid = user.uid;
var updates = {};
updates['foods' + '/' + item.$key + '/' + 'state' + '/' + uid] = postData;
return firebase.database().ref().update(updates);
}
I want to create a query that only shows the data corresponding to that UID. In a previous query I was using:
getLists(): FirebaseListObservable<any> {
return this.db.list('/foods', {
query: {
orderByChild: 'state',
equalTo: 'listed'
}
});}
This is the structure of my database:
{
"foods" : {
"foodID1" : {
"category" : "Produce",
"foodname" : "Apples",
"state" : {
"aePQkvozV6gehP7ihjN0OWCltKu2" : {
"state" : "listed"
}
}
},
"foodID2" : {
"category" : "Dairy",
"foodname" : "Cheese",
"state" : {
"aePQkvozV6gehP7ihjN0OWCltKu2" : {
"state" : "listed"
}
}
}
}
}
What do I need to do to show the items that correspond to a signed in user's UID?
The orderByChild property can take a path. So the code then simple becomes:
getLists(): FirebaseListObservable<any> {
return this.db.list('/foods', {
query: {
orderByChild: 'state/'+firebase.auth().currentUser.uid+'/state',
equalTo: 'listed'
}
});
}
This requires that the user is signed in of course. To test the query without a signed-in user, you can use a hard-coded value:
getLists(): FirebaseListObservable<any> {
return this.db.list('/foods', {
query: {
orderByChild: 'state/aePQkvozV6gehP7ihjN0OWCltKu2/state',
equalTo: 'listed'
}
});
}

Firebase key reference

I am trying to add a simple transaction to a firebase database, however, I'm not having luck getting around the firebase generated keys for each account. here is my JSON:
{
"accounts" : {
"-KRPSyO4B48IpBnHBTYg" : {
"newRecord" : "100",
"email" : "",
"provider" : "",
"userId" : ""
}
},
"products" : {
"-KUKRafaNurpFhGF4jQa" : {
"name" : ""
}
},
}
I want to add a count to "newRecord" to the same level as userId, provider and email. However I am not successful with the following, or any variation so far:
firebase.database().ref('accounts/' + accounts.id).transaction(function(value) {
if (value) {
value.newRecord++;
}
return value;
});
Thanks in advance!
You should refer the value directly while using the transaction.
firebase.database().ref('accounts/' + accounts.id+'/newRecord').transaction(function(value) {
if (value) {
value++;
}
return value;
});

how do i replace some properties returned from database in sails

So i'm trying to replace fields on the data queried from the database in sails.
async.waterfall( [
function getscores(callback) {
Score.find({course : courseId}).paginate({page : 1 , limit: 10}).populate('course')
.exec(function(err,data) {
callback(null,data);
});
}
, function addUserInfo(result,callback) {
for(var i=0; i < result.length; i++){
result[i].user = User.findOne({id : result[i].user}).exec(function(err,data) {
var temp = {
"name" : data.name,
"id" : data.id,
"user_id" : data.user_id
}
return temp;
});
}
res.json(messageGenerator(200, 'Sucecss', result));
}],function(err) {
console.log(err);
}
);
the first function 'getScores' returns the scores array but each score property only has a user id. Now in addUserInfo function, i want to be able to add the user's name to the score property.
But the above code fails to return the users inside. the user property of score is empty. i believe the response is already sent before the program gets to add the user property ( due to asyncronousness of the database adapter).
Following a brief comment chat, the following replacement for the addUserInfo function should help you achieve what you desire:
function addUserInfo(results,callback) {
async.map(results, function(result, callback) {
User.findOne({id : result.user}).exec(function(err, data) {
callback(err, Object.assign(result, {
"user": {
"name" : data.name || null,
"id" : data.id || null,
"user_id" : data.user_id || null
}
}));
});
}, function(err, output) {
return res.json(messageGenerator(200, "Success", output))
});
}
Async map allows us to asynchronously iterate over results, allowing us to amend the result by supplying the callback with the new result as the second parameter. The Final function is our final callback, that gets provided with any err's that have occured along the way and our new Array as output.

Mongodb - Search by id and embedded array value

Im trying to write a function that will search for an object by ID and whether or not a value is contained in an embedded array within the object.
{
"_id" : ObjectId("569bea91c0e1fee4063527ac"),
"user" : ObjectId("568c65174fee132c36e199dd"),
"votes" : 9,
"image" : "./modules/deals/client/img/uploads/1546f914dba7e1732ea853cd70d79148.jpg",
"price" : "12.95",
"retailer" : "argos.co.uk",
"voters" : [{
"user" : ObjectId("568c65174fee132c36e199dd"),
},
{
"user" : ObjectId("568c65174fee132c36e199dd"),
},
{
"user" : ObjectId("568c65174fee132c36e199dd"),
}]
I would like to search by the _id and the voters.user.
I believe i need to finish this function correctly
exports.dealByIdAndVoter = function(req, res) {
Deal.count({
$where: function () {
}
},
function(err, dealByIdAndVoter) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
console.log(dealByIdAndVoter);
var data = {};
data.count = dealByIdAndVoter;
res.json(data);
}
});
};
If you do not need to use the $where function, you can construct the query with the $or operator in this manner:
Deal
.find({
$or: [
// Match by _id
{ _id: req.id },
// Match by any user in the 'voters' array with a matching 'user' field.
{ 'voters.$.user': req.id }
]
})
.count(function(err, count) {
// Handle error here
res.json(count);
});

Mongoose add filter to insert in node.js

I have a array of data need to be inserted to mongodb. But the array has some data have already existed in mongodb. How to insert this array of data only the parts which not existed in mongodb. The struct is like below:
[
{
"_id" : ObjectId("551ca2b973d1124a0445f491"),
"url" : "http://ww1.sinaimg.cn/thumbnail/ddf0f092gw1eqqyykbezwg20bu06px6u.gif",
"createdAt" : ISODate("2015-04-02T02:00:25.395Z"),
},
{
"_id" : ObjectId("551ca2b973d1124a0445f492"),
"url" : "http://ww2.sinaimg.cn/thumbnail/ddf0f092jw1eqqyz3c2bfg20b4068hdz.gif",
"createdAt" : ISODate("2015-04-02T02:00:25.401Z"),
"__v" : 0
}
]
For example the first document's url has already existed in mongodb, how to add a filter or exclude it from the array and then insert it into the mongodb.
My current insert code like below:
var imgDicts = [];
for (var i = 0; i < imgs.length; i++) {
var img = imgs[i].img;
var imgDict = {url: img, createdAt: Date.now()};
imgDicts.push(imgDict);
};
console.log(imgDicts);
Img.collection.insert(imgDicts, function(err, docs){
if (err) {
callback(err, null);
} else {
callback(null, {message: 'success'});
}
});

Categories

Resources