$in is not working in loopback - arrays

I have an array of string as follows:
['57b69c9d4ae615ef0e312af6','57b69bf477b8e5cd0eb38c88'];
I am converting this into ObjectId as follows:
var objectIds = [];
for(var i=0; i<expenseIds.length; i++){
var _id = new ObjectId(expenseIds[i]);
objectIds.push(_id);
}
objectIds:
[ 57b69c9d4ae615ef0e312af6, 57b69bf477b8e5cd0eb38c88 ]
Now i am using $in query in mongoDb to fetch all the details as follows:
app.models.xxxxx.find({"_id" : {"$in" : objectIds}}, function(err, res){
if(err){
} else {
console.log(res);
}
});
But its not filtering. All the documents in the collection xxxxx is returning.. Please share your ideas. Thanks in advance.
EDIT:
when i am running the command in mongo shell:
db.xxx.find({ _id: { '$in': [ 57b69c9d4ae615ef0e312af6, 57b69bf477b8e5cd0eb38c88 ] }});
It throws error:
SyntaxError: identifier starts immediately after numeric literal #(shell):1:35

You need to enable allowExtendedOperators for your model.
//model.json
...
"options": {
"validateUpsert": true,
"mongodb": {
...
"allowExtendedOperators": true
}
},
...
UPDATE
Also there is a problem with your filter.
app.models.xxxxx.find({where: {"_id" : {"$in" : objectIds}}}, function(err, res){
if(err){
} else {
console.log(res);
}
});
Also you use built-in operators :
app.models.xxxxx.find({where: {id : {inq : objectIds}}}, function(err, res){
if(err){
} else {
console.log(res);
}
});

if you are using mongoose then try this
var objectIds = [];
for(var i=0; i<expenseIds.length; i++){
var _id = mongoose.Types.ObjectId(expenseIds[i]);
objectIds.push(_id);
}
or simply you can do this using MongoDb
var ObjectId = require('mongodb').ObjectID;
var objectIds = [];
for(var i=0; i<expenseIds.length; i++){
var _id = ObjectId(expenseIds[i]);
objectIds.push(_id);
}
please do let me know if this solves your problem

Related

In NodeJS, convert database query output to Json format

This is my code:
oracledb.getConnection(
{
user : "user",
password : "password",
connectString : "gtmachine:1521/sde1"
},
function(err, connection)
{
if (err) { console.error(err); return; }
connection.execute(
"SELECT filetype, filetypeid from filetype where filetypeid < 6",
function(err, result)
{
if (err) { console.error(err); return; }
response = result.rows;
console.log(response);
res.end(JSON.stringify(response));
});
This is the output
[["Ascii Text",1],["Binary",2],["Graphics - GIF",3],["Graphics - JPEG",4],["HTML",5]]
But my front end angularjs is expecting something in this format:
[{"filetype":"Ascii Text","filetypeid":1},{"filetype":"Binary","filetypeid":2}]
Does any one know what is the standard way to convert this?
These will convert your array of arrays into an array of objects:
var results = [["Ascii Text",1],["Binary",2],["Graphics - GIF",3],["Graphics - JPEG",4],["HTML",5]];
results = results.map(
function(item) {
return {
filetype: item[0],
filetypeid: item[1]
}
}
);
console.log(results);
And in ES6:
var results = [["Ascii Text",1],["Binary",2],["Graphics - GIF",3],["Graphics - JPEG",4],["HTML",5]];
results = results.map(item => ({filetype: item[0], filetypeid: item[1]}));
console.log(results);

Mongoose stops to $push to array if the field already exists in a document

I am using Node and Mongoose, and trying to set an array of ISODate elements:
"visitLog" : [
ISODate("2017-10-22T22:43:49.571Z"),
ISODate("2017-10-22T22:44:39.572Z"),
ISODate("2017-10-22T23:35:36.111Z"),
ISODate("2017-10-22T23:48:26.516Z"),
ISODate("2017-10-22T23:50:33.378Z"),
ISODate("2017-10-22T23:53:56.227Z"),
ISODate("2017-10-22T23:57:20.986Z")
]
So I had an existing schema where visitLog field did not existed, added new field to a schema - visitLog: [ {type: Date, default: '' }],and it worked - the result is what you see above.
But when I created a new document with updated schema that already has an empty array in it - "visitLog" : [ ] , $push just stopped working.
Here is mongoose query, if needed:
// conditions is a ternary operator that checks whether req.body username
// is an email or not, and puts needed condition to a query
var conditions = (!/^[a-zA-Z0-9\-\_\.\+]+#[a-zA-Z0-9\-\_\.]+\.[a-zA-Z0-9\-\_]+$/.test(req.body.username)) ? ' {email: req.body.username } ' : ' {username: req.body.username } ';
var fieldsToSet = {
$push: {
visitLog: new Date().toISOString(),
}
};
var options = { upsert: true };
User.findOneAndUpdate(conditions, fieldsToSet, options, function(err, user) { ...
The working document was created in mongo console, while the second was generated on a server, but I can't how can this make any difference.
Using $push shuld work with empty arrays. Can someone explain what's wrong here?
Thank you.
Edit
It figures that using findByIdAndUpdate without conditions works for both documents:
var fieldsToSet = {
$push: {
visitLog: new Date().toISOString(),
}
};
var options = { new: true };
req.app.db.models.User
.findByIdAndUpdate(req.user.id, fieldsToSet, options, function(err, user) {
You can do with the following query.
User.findOne(condiitons, (err, user) => {
if (user) {
var date = new Date().toISOString();
user.visitLog.push(date);
user.save();
...
}
});

how to make primary key / _id optional to input in mongoose

I want make primary key no need to input but primary key auto generate in mongodb.
so, i use {type : ObjectId,required:false}, but it wont work because I let the primary key empty. so is there another ways to make pprimary key optional to input? Thankyou
rest api model
var mongoose = require("mongoose");
var Schema = mongoose.Schema;
var ObjectId = Schema.ObjectId
var accessmenu = new Schema({
_id : {type : ObjectId,required: false},
acc_id : String,
name : String,
read : Boolean,
execute : Boolean
},{ collection: 'access_menu'});
var accessmenu = mongoose.model("accessmenu",accessmenu);
module.exports.accessmenu = accessmenu;
rest api
app.put("/access_menu/:id",function(req,res){
var AccessMenu = new accessmenu({
_id : req.body._id,
acc_id : req.body.acc_id,
name : req.body.name,
read : req.body.read,
execute : req.body.execute
});
AccessMenu.save(function(err){
if(err)
{
accessmenu.update({_id : req.params.id},{$set:{acc_id : req.body.acc_id,
name : req.body.name,
read : req.body.read,
execute : req.body.execute
}},function(err,users){
if(err)
{
data['error'] = 1;
data['Access_Menu'] = "update faill";
res.json(data);
}
else
{
data['error'] = 0;
data['Access_Menu'] = "update success";
res.json(data);
}
});
}
else
{
data['error'] = 0;
data['Access_Menu'] = "input success";
res.json(data);
}
});
});
script.js
if($scope.data_acc_lv.length > 0)
{
for(var i = 0;i<$scope.data_acc_lv.length;i++)
{
var input3 = {
"_id" : $scope.data_acc_lv[i]._id,
"acc_id":$scope.accLvID,
"name": $scope.data_acc_lv[i].name,
"read": $scope.data_acc_lv[i].read,
"execute": $scope.data_acc_lv[i].execute
}
$http.put("http://localhost:22345/access_menu/" + $scope.data_acc_lv[i]._id,input3)
.success(function(res,err){
if(res.error == 0)
{
$scope.data_acc_lv.length = 0;
}
else
{
console.log(err);
}
});
}
}
Mongoose assigns each of your schemas an _id field by default if one is not passed into the Schema constructor. The type assigned is an ObjectId to coincide with MongoDB's default behavior.
If you don't want an _id added to your child schema at all, you may disable it using this option.
// disabled _id
var childSchema = new Schema({ name: String }, { _id: false });
var parentSchema = new Schema({ children: [childSchema] });
You can only use this option on sub-documents. Mongoose can't save a document without knowing its id, so you will get an error if you try to save a document without an _id.
http://mongoosejs.com/docs/guide.html

How to update mongoDB from post()

I am creating a MEAN Stack application. My post function is as follows:
app.post('/updateGroup/:id', function(req, res) {
var id = req.params.id; // = mongoDB ObjectID ie: "55616e2a37e8728266ceac6"
var vals = {};
vals['hostName'] = req.body.hostName // = a String ie, "Steve"
// this is a different name value than the
// current hostName key that is in
// the groupList db
db.groupList.update(
{"_id": id},
{$set : vals},
function(err, result) {
if (err) {
console.log(err);
}
else {
console.log(result);
}
}
);
});
When I access this function in my front-end Angular code my
console.log(result);
Comes out as:
{ ok: true, n: 0, updatedExisting: true }
But I should see n: 1 to indicate there was an update? Why is my Node application not updating my mongoDB key:value pair?
Is there something about db.collection.update() that I'm missing?
I was able to figure it out:
When assigning the _id query I needed to do it like this:
id['_id'] = mongojs.ObjectId(req.params.id);

Mongodb query doesn't work

In my image sharing application you can upload images and create albums. When you delete an image from the site it shall also be deleted in the albums (the ones that has got the image in it).
Below is the route for deleting an image, and what I really need help with is why the code for deleting the images (imageName and imageId) in the albums below doesn't work.
Thanks in advance!
The models:
var AlbumSchema = new Schema({
title : String,
imageName : [String],
imageId : [String]
});
modelObject.AlbumSchema = AlbumSchema;
modelObject.Album = mongoose.model('Album', AlbumSchema);
-
var BlogPostSchema = new Schema({
name : String,
size : Number,
type : String,
author : ObjectId,
title : String
});
modelObject.Comment = mongoose.model('Comment', CommentSchema);
modelObject.BlogPost = mongoose.model('BlogPost', BlogPostSchema);
The part that doesn't work in the code below is the following:
albums[i].imageName.remove(j);
albums[i].imageId.remove(j);
albums[i].save(function (err){
if (err) {
console.log(err);
// do something
}
});
Full code:
app.get('/blog/delete/:id', function(req, res){
model.BlogPost.findById(req.params.id, function (err, blog){
var theImage = blog.name;
var query = albumModel.Album.find( { imageName:theImage } )
query.exec(function (err, albums) {
if (!albums) {
blog.remove(function(err) {
console.log(err);
// do something
});
res.redirect('/blogs');
}
else {
for (var i = 0; i < albums.length; i++) {
for (var j = 0; j< albums[i].imageName.length; j++){
if (theImage == albums[i].imageName[j]){
albums[i].imageName.remove(j);
albums[i].imageId.remove(j);
albums[i].save(function (err){
if (err) {
console.log(err);
// do something
}
});
}
}
}
}
blog.remove(function(err) {
console.log(err);
// do something
});
res.redirect('/blogs');
});
});
});
JavaScript arrays don't have a remove method so I would expect your code may be crashing. You should be using code like albums[i].imageName.splice(j, 1); instead.

Resources