How to use $in in mongoose reference schema - node.js

I have 2 schemas 1st is city and second is pincode. Pincode having reference of city. They both look like this
CITY schema
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
// create a all city list
var allCitySchema = new Schema({
cities: {
type: String
}
}, {collection: 'allcities'});
var allcities = mongoose.model('allcities', allCitySchema);
module.exports = allcities;
Pincode schemas
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var allPincode = new Schema({
city_id: {
type: Schema.ObjectId,
ref: 'allcities'
},
pincode: {
type: String
}
}, {collection: 'pincode'});
var allPincode = mongoose.model('pincode', allPincode);
module.exports = allPincode;
Now the problem is when i tried to fetch all pincode based upon city id for that i tries like this
app.post('/api/getPincodeByCity', function(req, res) {
console.log("In pincode");
var cities_id = [];
cities_id = req.body.cities_id;
console.log(req.body); // { cities_id: '["5597aa08c0a0beb40be128d4","5597aa2bbb18fefc142b6915"]' }
console.log(cities_id);
pincodes.findById( {city_id: { $in: cities_id }}, function(err,pincodeIds){
if(err) res.send(err.message);
res.send(pincodeIds);
res.end('{"success" : "Recieved Successfully", "status" : 200}');
});
});
But it's not working its giving me this error
Cast to ObjectId failed for value "[object Object]" at path "_id"
I also try with find() instead of findById() method but it giving me this error
undefined is not a function

The $in operator is not just "strictly" for querying arrays as that can be done with basically any operator for a singular value.
It's actually a "list of arguments" which evaluates to an $or condition, but with shorter syntax:
var idList = ["559e0dbd045ac712fa1f19fa","559e0dbe045ac712fa1f19fb"];
var pincode = mongoose.model('pincode');
pincode.find({ "city_id": { "$in": idList } },function(err,docs) {
// do something here
});
Which as mentioned is short form for this:
pincode.find(
{
"$or": [
{ "city_id": "559e0dbd045ac712fa1f19fa" },
{ "city_id": "559e0dbe045ac712fa1f19fb" }
]
},
function(err,docs) {
// do something here
}
)
You are getting an error because you are overwriting the "array" definition with a "string" which is what all "request" objects are unless parsed otherwise.
The other reason for the error is you are calling the wrong method. .findById() expects a single argument of the _id for the document. To query other fields use .findOne() or in this case .find() since an $in will possibly match more than one document.

Related

Get the _id of the sub-document from mongoose findOne query

The schema of my Sample model is:-
var nameSchema = new mongoose.Schema({
firstname:String,
lastname:String
})
var sampleSchema= new mongoose.Schema({
number: {
type: String
},
name :{
type : [nameSchema]
}
});
I am trying to update the first and last name by searching them by their number property by making use of Sample.findOne({number:number}). And i am performing the update operation in the following manner:-
module.exports.updateNumber = function(req, res){
var number= req.body.number;
var lname= req.body.lname;
var fname= req.body.fname;
Sample
.findOne({number:number})
.select('name')
.exec(function(err, doc){
console.log(doc)
var this_id;
var thisService = doc.name.id('this_id');
thisService.firstname=fname;
thisService.lastname=lname;
doc.save(function(err, update) {
if (err) {
res
.status(500)
.json(err);
} else {
res
res.render('done')
}
});
})
}
If i console log the output i got is:
{ _id: 5bc5d71f47ff14361c0639d1,
name:
[ { _id: 5bc5d71f47ff14361c0639d2,
firstname: 'firstname',
lastname: 'lastname' } ] }
Is there any way, i could store _id: 5bc5d71f47ff14361c0639d2 in 'this_id' variable, so that this updation would be possible
name is an array, so if you want the first _id then name[0]._id would suffice, if you want an array of all values for _id in name, then name.map((person) => person._id) would give you an array of _id
However, more details about the context of this object would help give a better answer.

$match _id is not working in Mongoose aggregate function

As my title, $match _id is not working in Mongoose aggregate function.
Could somebody please help me?
Is this related to mongoose version?
I use 4.9.2.
I need to use aggregate because I will group by the result after processing the $match.
I already saw posts before, but manually casting didn't work for me!
Here is my schema:
var mongoose = require("mongoose");
var moment = require("moment");
var Schema = mongoose.Schema;
var AvgDailyCharging = new Schema({
_id : {
date: Date,
storeID: {
type: Schema.Types.ObjectId,
ref: 'store'
}
},
chargers: [{
transmitterID: {
type: Schema.Types.ObjectId,
ref: 'device'
},
minutes: Number
}],
});
mongoose.model('AvgDailyCharging', AvgDailyCharging);
And here is the query:
var Mongoose = require('mongoose');
var Model = require('../db/model');
var Query = require('../db/query');
var RESULT_LIMIT = 2000; // Limit the return data size
exports.getAvgDailyCharging = function(req, res) {
var id = new Mongoose.Types.ObjectId("58b43fdf0fd53910121ca6f4");
var query = new Query("AvgDailyCharging");
query.aggregate([
{
$match: {
"_id.storeID": id, //HELP!!!!!
"_id.date": { //match only by this works fine.
$gte: new Date(req.params.startTime),
$lt: new Date(req.params.endTime)
}
}
}
]).exec(function(error, data) {
if (error) {
res.send({result:'ERROR', message: error});
} else {
res.send(data);
}
});
}
Please help me!!!! I was stuck for several hours! Q_Q
When I was testing in mongoose version 4.4.4, both type casting and string didn't work. However, after I update it to the version 4.9.2, type casting is no needed, and directly using a string in $match _id works!
Update:2017-03-31
I think another problem in my scenario is my schema definition. Since this collection, say A, is created from another one, say B, using $group: { _id: { storeID: "$storeID" } } where the storeID field in collection B is of type ObjectId, then in collection A I find out that _id.store is actually a String not an ObjectId, so the best way is to change the schema I mentioned in the question to:
var AvgDailyCharging = new Schema({
_id : {
date: Date,
storeID: String
},
chargers: [{
transmitterID: {
type: Schema.Types.ObjectId,
ref: 'device'
},
minutes: Number
}],
});

MongoDB / Mongoose $pull (remove) Sub Document not working

Smashing my head into the keyboard over this.
Simply need to remove subdocument. Example below only has one item in OnCommands but there could be a many items there. I have tried find, findbyid, updatebyId, pull, one things after another. Tried by _id of subdoc and by generic searchinMost simple run without doing anything no errors.
I would be so greatful if you can show me what I am doing wrong, it's the last part of my code that isn't work.
Sample Data:
> db.EntryPoints.find({_id: ObjectId("569e4fabf1e4464495ebf652")}).pretty()
{
"__v" : 0,
"_id" : ObjectId("569e4fabf1e4464495ebf652"),
"name" : "bbbb",
"offCommands" : [ ],
"onCommands" : [
{
"data" : "11111",
"operation" : "on",
"command" : "ISY-HTTPGet",
"_id" : ObjectId("569e4faff1e4464495ebf653")
}
]
Model:
var mongoose = require('mongoose');
var Schema = mongoose.Schema,
ObjectId = Schema.ObjectId;
var onCommandsSchema = new Schema({
command: String
,operation: String
,data: String
})
var offCommandsSchema = new Schema({
command: String
,operation: String
,data: String
})
mongoose.model('onCommands', onCommandsSchema);
mongoose.model('offCommands', offCommandsSchema);
// create a schema
var EntryPointsSchema = new Schema({
name: String
,onCommands: [onCommandsSchema]
,offCommands: [offCommandsSchema]
,description: String
}, { collection: 'EntryPoints' });
mongoose.model('EntryPoints', EntryPointsSchema);
var EntryPoints = mongoose.model('EntryPoints');
module.exports = EntryPoints;
Node Post Code:
router.post('/webservices/removeCommand', function (req, res) {
var EntryPoints = require('../data_models/automate_entrypoints.js');
EntryPoints.update(
{ _id: ObjectId(req.body._id) }
, {
$pull: {
onCommands: { id_: req.body._id }
}
}
, function (err, ouput) { console.log("data:", numAffected) }
);
});
Your code won't work because of the query part of your update: you want to match on the embedded document's _id, not on the main document. So change it to
var EntryPoints = require('../data_models/automate_entrypoints.js');
EntryPoints.update(
{ "onCommands._id": req.body._id },
{
"$pull": {
"onCommands": { "_id": req.body._id }
}
},
function (err, numAffected) { console.log("data:", numAffected) }
);

Nodejs: Moongoose can't find the object

So I have a mongodb on mongolabs that looks something like this:
under the collection "news"
[{
"_id": {
"$oid": "542aab88e4b0e67da1edd1bd"
},
"year": 2014,
"data": {
"someinfo":"cool info"
}
}]
And on node I have the following:
//dependencies
var mongoose = require("mongoose");
var Schema = mongoose.Schema;
//Setting up the schemas
var newsSchema = new Schema({
year: String,
data: Object
});
mongoose.model('news',newsSchema);
//routes
var mongolabs = express.Router();
mongolabs.route('/List/:type1/:year')
.get(function(req, res){
mongoose.model(req.params.type1).find({year:req.params.year}, function(err,suc) {
res.jsonp(suc);
});
});
app.use('/mongo', mongolabs);
unfortunately when I go http:///mongo/List/news/2014, it returns empty.
I already tried everything I can think of, needless to say I am a newbie to mongoose, node and mongodb.
You're trying to query for a number value with a string value, hence the empty results.
Try casting the req.params.years as a number by adding the unary plus before your param.
{ year: +req.params.year }
You also could use the parseInt() function:
var year = parseInt(req.params.years, 10);
Probably you're passing null to the .find() method.
You're doing this:
{ year: req.params.type1.year }
,when you should be doing:
{ year: req.params.year }

How to set ObjectId as a data type in mongoose

Using node.js, mongodb on mongoHQ and mongoose. I'm setting a schema for Categories. I would like to use the document ObjectId as my categoryId.
var mongoose = require('mongoose');
var Schema = mongoose.Schema,
ObjectId = Schema.ObjectId;
var Schema_Category = new Schema({
categoryId : ObjectId,
title : String,
sortIndex : String
});
I then run
var Category = mongoose.model('Schema_Category');
var category = new Category();
category.title = "Bicycles";
category.sortIndex = "3";
category.save(function(err) {
if (err) { throw err; }
console.log('saved');
mongoose.disconnect();
});
Notice that I don't provide a value for categoryId. I assumed mongoose will use the schema to generate it but the document has the usual "_id" and not "categoryId". What am I doing wrong?
Unlike traditional RBDMs, mongoDB doesn't allow you to define any random field as the primary key, the _id field MUST exist for all standard documents.
For this reason, it doesn't make sense to create a separate uuid field.
In mongoose, the ObjectId type is used not to create a new uuid, rather it is mostly used to reference other documents.
Here is an example:
var mongoose = require('mongoose');
var Schema = mongoose.Schema,
ObjectId = Schema.ObjectId;
var Schema_Product = new Schema({
categoryId : ObjectId, // a product references a category _id with type ObjectId
title : String,
price : Number
});
As you can see, it wouldn't make much sense to populate categoryId with a ObjectId.
However, if you do want a nicely named uuid field, mongoose provides virtual properties that allow you to proxy (reference) a field.
Check it out:
var mongoose = require('mongoose');
var Schema = mongoose.Schema,
ObjectId = Schema.ObjectId;
var Schema_Category = new Schema({
title : String,
sortIndex : String
});
Schema_Category.virtual('categoryId').get(function() {
return this._id;
});
So now, whenever you call category.categoryId, mongoose just returns the _id instead.
You can also create a "set" method so that you can set virtual properties, check out this link
for more info
I was looking for a different answer for the question title, so maybe other people will be too.
To set type as an ObjectId (so you may reference author as the author of book, for example), you may do like:
const Book = mongoose.model('Book', {
author: {
type: mongoose.Schema.Types.ObjectId, // here you set the author ID
// from the Author colection,
// so you can reference it
required: true
},
title: {
type: String,
required: true
}
});
My solution on using ObjectId
// usermodel.js
const mongoose = require('mongoose')
const Schema = mongoose.Schema
const ObjectId = Schema.Types.ObjectId
let UserSchema = new Schema({
username: {
type: String
},
events: [{
type: ObjectId,
ref: 'Event' // Reference to some EventSchema
}]
})
UserSchema.set('autoIndex', true)
module.exports = mongoose.model('User', UserSchema)
Using mongoose's populate method
// controller.js
const mongoose = require('mongoose')
const User = require('./usermodel.js')
let query = User.findOne({ name: "Person" })
query.exec((err, user) => {
if (err) {
console.log(err)
}
user.events = events
// user.events is now an array of events
})
The solution provided by #dex worked for me. But I want to add something else that also worked for me: Use
let UserSchema = new Schema({
username: {
type: String
},
events: [{
type: ObjectId,
ref: 'Event' // Reference to some EventSchema
}]
})
if what you want to create is an Array reference. But if what you want is an Object reference, which is what I think you might be looking for anyway, remove the brackets from the value prop, like this:
let UserSchema = new Schema({
username: {
type: String
},
events: {
type: ObjectId,
ref: 'Event' // Reference to some EventSchema
}
})
Look at the 2 snippets well. In the second case, the value prop of key events does not have brackets over the object def.
You can directly define the ObjectId
var Schema = new mongoose.Schema({
categoryId : mongoose.Schema.Types.ObjectId,
title : String,
sortIndex : String
})
Note: You need to import the mongoose module
Another possible way is to transform your _id to something you like.
Here's an example with a Page-Document that I implemented for a project:
interface PageAttrs {
label: string
// ...
}
const pageSchema = new mongoose.Schema<PageDoc>(
{
label: {
type: String,
required: true
}
// ...
},
{
toJSON: {
transform(doc, ret) {
// modify ret directly
ret.id = ret._id
delete ret._id
}
}
}
)
pageSchema.statics.build = (attrs: PageAttrs) => {
return new Page({
label: attrs.label,
// ...
})
}
const Page = mongoose.model<PageDoc, PageModel>('Page', pageSchema)
Now you can directly access the property 'id', e.g. in a unit test like so:
it('implements optimistic concurrency', async () => {
const page = Page.build({
label: 'Root Page'
// ...
})
await page.save()
const firstInstance = await Page.findById(page.id)
const secondInstance = await Page.findById(page.id)
firstInstance!.set({ label: 'Main Page' })
secondInstance!.set({ label: 'Home Page' })
await firstInstance!.save()
try {
await secondInstance!.save()
} catch (err) {
console.error('Error:', err)
return
}
throw new Error('Should not reach this point')
})

Resources