How do I perform a find query in Mongoose? - node.js

i have a collection of Ebooks data in mongodb like
{
"_id" : ObjectId("58b56fe19585b10cd42981d8"),
"cover_path" : "D:\\Ebooks\\uploads\\ebooks\\cover\\1488285665748-img1-700x400.jpg",
"path" : "D:\\Ebooks\\uploads\\ebooks\\pdf\\1488285665257-Webservices Natraz.pdf",
"description" : "ebook",
"title" : "book name",
"tag" : [
"Hindi",
"Other"
],
"__v" : NumberInt(0)
}
Now i want to search something if keyword is little bit match from "title:" then show all related books object.
My Mongoose schema is :-
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var EbookSchema = new Schema({
title: {type:String},
description: {type:String},
path: {type:String,required:true},
cover_path: {type:String,required:true},
tag: [{ type: String }]
});
module.exports = mongoose.model('Ebook', EbookSchema);
I try :-
app.get('/ebook?search=',function(req,res){
var search_key = req.param('search');
Ebook.find(title:'search',function(err, ebooks) {
if (err)
res.send(err);
res.json(ebooks);
});
});
but i found null how can i do ? i only want when i search a little-bit keyword i found all related object .

Try wrapping your query in curlies, Mongoose expects an object as the query.
app.get('/ebook?search=',function(req,res){
var search_key = req.param('search');
Ebook.find({title: search_key})
.then(ebooks => res.json(ebooks))
.catch(err => res.status(404).json({ success: false }));
});

Related

MongoDB and mongoose: how to add an object if it doesn't already exist

I am having some trouble with mongoDB/mongoose and node.js. I am used to SQL, and mongoDB is...hard! Here is my schema:
var mongoose = require('mongoose');
mongoose.Promise = global.Promise;
var itemSchema= mongoose.Schema({
item_info : {
user_id : Number,
location : String,
item_id : Number,
title : String
},
item_hist : {
user_id : Number,
location : String,
item_id : Number,
founddate : String
}
});
module.exports = mongoose.model('item', itemSchema);
And I can add a new item by doing this:
var item= require('./app/models/item');
var item= new item();
item.item_info.user_id = 12345;
item.item_info.location = 'This address';
item.item_info.item_id = 4444;
item.item_info.title = 'New item';
item.save(function(err)
{
if (err) throw err;
});
What I want to be able to do is say: "look for an item with item_info.item_id 5555. if it exists, do nothing. if it doesn't exist, then add it to the database." I've read through so much mongodb and mongoose documentation, but between using dot notation and accessing through nodejs instead of command line mongodb, I still can't figure out how to do this. SQL seemed so much easier!
Just use this -
var query = { user_id: 12345, location: "This address", item_id: 4444, title: "New item" },
options = { upsert: true };
Model.findOneAndUpdate(query.item_id, query, options, function(error, result) {
if (error) return;
// do something with the document
});

Mongoose returns empty while the same query in mongodb shell works fine

I know maybe this question has been asked quite many times here, I've went through several solutions people came with to similar questions but none of them seemed to help in my case.
I have two collections called users and posts and models for them look like this:
users
var mongoose = require('mongoose').set('debug', true);
var Schema = mongoose.Schema;
var usersSchema = new Schema({
name: {type: String, required: true}
});
var User = mongoose.model('user', usersSchema, 'users');
module.exports = User;
posts
var mongoose = require('mongoose').set('debug', true);
var Schema = mongoose.Schema;
var postsSchema = new Schema({
content: String,
user: {
type: Schema.ObjectId,
ref: 'users',
required: true
}
});
var Post = mongoose.model('post', postsSchema, 'posts');
module.exports = Post;
I'm trying to get the posts of a user using this code:
var Post = require('../models/posts');
...
router.get('/posts/user/:userId', function (req, res, next) {
Post.find({user: req.params.userId}, function (err, posts) {
Post.populate(posts, {path: 'user'}, function(err, posts) {
res.send(posts);
});
});
});
Mongoose debug mode reports that the following query is executed during the request:
posts.find({ user: ObjectId("592e65765ba8a1f70c1eb0bd") }, { fields: {} })
which works perfectly fine in mongodb shell (I'm using Mongoclient) but with Mongoose this query returns an empty array.
The query I run in mongodb shell:
db.posts.find({ user: "592e65765ba8a1f70c1eb0bd" })
The results I get:
{ "_id" : ObjectId("592e66b48f60c03c1ee06445"), "content" : "Test post 3", "user" : "592e65765ba8a1f70c1eb0bd" }
{ "_id" : ObjectId("592e66b98f60c03c1ee06446"), "content" : "Test post 4", "user" : "592e65765ba8a1f70c1eb0bd" }
{ "_id" : ObjectId("592e66bb8f60c03c1ee06447"), "content" : "Test post 5", "user" : "592e65765ba8a1f70c1eb0bd" }
I'm at the very beginning on learning Node.JS and MongoDB, so maybe I've missed something.
Thank you in advance!
As Neil Lunn suggested, I checked the user field type and it was indeed of type String instead of ObjectId so there was a mismatch of types between the data stored in collection and the field type from the query.
I used this code to convert the user field type from String to ObjectId in my collection:
db.getCollection('posts').find().forEach(function (post) {
db.getCollection('posts').remove({ _id : post._id});
tempUserId = new ObjectId(post.user);
post.user = tempUserId;
db.getCollection('posts').save(post);
}
);
Now everything works as expected.

how do I populate a document mongoose or save refs

I have a questions collection and I have a store model. I want the questions field in the Store model to be to be the array of object ids from the questions collection. so I could use populate later. when I do app.get in the future it should show me a doc with the store info and all the questions.
var Schema = mongoose.Schema;
var storeSchema = Schema({
name : {type : String},
industry : {type : String},
questions :[{type : Schema.Types.ObjectId, ref : "Questions" }]
})
var questionsSchema = Schema({
question : {type :String}
})
var store = mongoose.model("Store", storeSchema);
var questions = mongoose.model("Questions", questionsSchema)
// questions.create({question: "question2"}, function(err,q){
// console.log("create: " , q)
// })
//something like this
questions.find({}, function(err, doc){
store.create({name : "store 1", industry : "industry 1" , questions : /*get the _ids from the question collection*/ {$push : doc.question}})
})
> db.questions.find().pretty()
{
"_id" : ObjectId("574534a289763c004643fa08"),
"question" : "question1",
"__v" : 0
}
{
"_id" : ObjectId("574534acc90f3f2c0c3d529b"),
"question" : "question2",
"__v" : 0
}
>
Population is the process of automatically replacing the specified paths in the document with document(s) from other collection(s). We may populate a single document, multiple documents, plain object, multiple plain objects, or all objects returned from a query.
var question = new Questions();
question.save(function(err) {
var store = new Store({
name:'sample',
industry:'tech',
questions: [question._id],
});
store.save(function(err){
//do whatever you would like, post creation of store.
});
});
Store.find(...).exec(function(err, stores) {
Questions.populate(stores, function(err, storesPostPopulate) {
// Now you have Stores populated with all the questions.
})
});
Since questions field in question schema is an array, you can always push another question id to it.
See mongoose populate
See mongoose Model populate

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

How to use $in in mongoose reference schema

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.

Resources