Question: How to install the mongoose?
npm install mongoose
Question: How to update the mongoose?
npm update mongoose
Question: How to Start the mongoose?
Include the mongoose in the project
var mongoose = require('mongoose');
Make the Db connection with mongodb
mongoose.connect('mongodb://localhost:27017/test'); var db = mongoose.connection;
Check the Error OR Success on Db Connection
db.on('error', console.error.bind(console, 'connection error:')); db.once('open', function() { console.log("MongoDB connected Successfully.!"); });
Question: How to Create Model with mongoose?
Here we have set the two fields only, you can add more if required.
var TodoSchema = mongoose.Schema({ id: String, //datatype is string name: String, //datatype is string }); var Todo = mongoose.model('Todo', TodoSchema);
In mongoose.model, the first argument is the singular name of the collection.
Mongoose automatically looks for the plural version with lowercase of your model name.
means for Todo, it will look todos.
Question: How to set unique key for a field?
var TodoSchema = mongoose.Schema({ id: { type: Number, unique: true}, name: String, //datatype is string });
Question: How to set unique key and required for a field?
var TodoSchema = mongoose.Schema({ id: { type: Number, unique: true }, email: { type: String, unique: true, required:true }, name: String, //datatype is string });
Question: How to list the records from mongodb?
var cursor = Todo.find({ }).cursor(); cursor.on('data', function(doc) { jsonData[doc.id] = doc.name; }); cursor.on('close', function() { console.log(jsonData); });
Question: How to save the record?
var TodoDetails = new Todo({ id: "10",name:"this id test message"}); TodoDetails.save(function (err) {if (err) console.log ('Error on save!')});
Question: How to update the record?
Todo.update({id: "10" }, { $set: { name: "this is update message" }}, {}, function(){ console.log("Update the records successfully"); })
Question: How to delete the record?
Todo.find({ id:"10" }).remove( function(){ console.log("Record deleted successfully"); });
Question: How to delete the document and check is it deleted?
Todo.find({ id:"10" }).remove( function(err, effectedRows){ if(err){ console.log("Unable to delete the record"); } if(effectedRows.n==0){ console.log("Zero Record deleted"); }else{ console.log("Record deleted successfully"); } });
Question: What are the difference between mongoose.model and mongoose.Schema?
Model is an object that gives you easy access to a collection, allowing you to query the collection and use the Schema to validate any documents you save to that collection. It is created by combining a Schema, a Connection, and a collection name.
Schema is an object that defines the structure of the documents that will be stored.
it enables you to define types and validators for all data.
Question: How to get first record(s) from listing?
Todo.findOne({ 'name': 'kumar' }, 'id', function (err, person) { if (err) return handleError(err); console.log(person); })
Question: How to fetch specific column?
Todo.find({ 'name': 'kumar' }, 'id name', function (err, person) { if (err) return handleError(err); //console.log(person); res.send(person); })
Question: How to limit the number of records?
You can use limit method.
Todo.find({}, 'id name', function (err, person) { if (err) return handleError(err); console.log(person); }).limit(3);
Question: How to get listing by name in ascending order?
You can use sort method, -1 means descending order, 1 means ascending order.
Todo.find({}, 'id name', function (err, person) { if (err) return handleError(err); console.log(person); }).limit(3).sort({ name: -1 });
Question: How to use "in" in where clause?
Todo.find({ name: { $in: ['arun', 'gupta']}, 'id name', function (err, person) { if (err) return handleError(err); console.log(person); }).limit(3).sort({ name: -1 });
Question: Give full Query example?
Todo.find({ occupation: /host/, 'name.last': 'Ghost', age: { $gt: 17, $lt: 66 }, name: { $in: ['technology', 'web'] } }, 'id name', function (err, person) { if (err) return handleError(err); //Here will be display all the records console.log(person); }).limit(3).sort({ name: -1 });
Question: How to create custom function in mongoose.model?
In schema/Model file (Create a custom function)
var TodoSchema = mongoose.Schema({ id: { type: Number, unique: true}, name: String, //datatype is string }); TodoSchema.statics.findByIdTest = function (todoId,cb) { return this.model('Todo').find({ id: todoId }, cb); };
How to use controller file.
Todo.findByIdTest(2677,function(error, data){ console.log(data); });