Nodejs, who started this week in Monday, has been studying for 5 days, and it's been a rookie period, and I've seen a lot of unexpected pits and lots of nodejs. Their content is too old for 2011-2013 years. Many statements module code framework is not used in a lot of pits through my Kind of pits pit pit finally made a very simple and practical express new version of the +mongoose and additions and deletions to the novice is very helpful code is 2015.
A problem that can be easily encountered when querying all the results of a document using Mongoose Articlecontents.getall = function (name, callback) { var query = {}; if (name) { query.name = name; } Articlecontentsmodel.find (///four parameters, where the second cannot be omitted (the second parameter is the result set to query out which document structure is included) Query,null, { so
Remember the following points before you begin
validation defined in SchemaType
Validation is an internal middleware
Validation occurs before document is to be save
Validation does not occur on null values unless the corresponding field is added with required validator
You can customize the validator
Built-in Validator
All SchemaType have required validators.
Number has min and Max validators
String has enum and match validator
Custom Validator
The restfull routes are as follows:Router.get ('/:id ', controller.show);The Mongoes code is as follows:function (req, res) { function ( err, notice){if(err) { Res.json ({no: 0,msg: ' Get failed: ' +err} '; } Else { var result = {no:1}; Result.obj=notice; Res.json (result); } );};Client Access:Http://192.168.0.165:9000/api/notices/11The printing results are as follows;{"no": 0,"msg": "Get failed: Casterror:cast to ObjectId failed for value \" 11\ "at path \" _id\
Objective
After watching the node.js actual combat, which in the data storage part of the Redis, Mongodb, I also wrote the book according to the introduction of a few simple demo, in the demo process first encountered the problem is the type of data and common curd writing. There are two ways to mongodb common operations, one is to use the API directly, and the same is that you use T-SQL to write SQL statements to manipulate the data, and then use the Mongo
Tags: model number res workaround why turn art description functionFirst, define a goods (commodity) of the models varMongoose = require ('Mongoose'); varSchema =Mongoose.
Schema; varProductschema =NewSchema ({"productId": String,"Producname": String,"Saleprice": Number,"productimage": String}); Module.exports=mongoose.model ("Good", Productschema,'Goods'); Two, in the definition of a users (user) models va
1, NPM start error, prompt port occupancyApp.js added App.listen (3000), delete can2. Skip to HTML pageEjs changed to Htmlapp.engine ('. html ', require (' Ejs ') __express); App.set (' View engine ', ' html ');Discover Route index.js file Add route router.get ('/login ', function (req, res, next) {Res.render (' login ', {title: ' Login '})3, the data is not queriedThe user collection does have data, but the query does notBased on the information collected online, try to save a piece of data and
For example, my code database code can be divided into Chinese and English sites. Each table has a site_code field to distinguish,
The two sites are deployed on different people servers. In this case, we will use system environment variables to differentiate them,
Set the environment variables in Mac
Vim ~ /. Bash_profile
Add a line of code export site_code = 'cn'
In UNIX, run the export site_code = 'cn' command on the terminal.
Enter the following command once after setting in Mac to see
Recently, you need to implement an HTTP service function in your project. Although you can implement HTTP sending and parsing by encapsulating the socket itself. However, considering that the network still has a large number of HTTP parsing source code, their own to achieve a little bit of trouble from scratch. So on the network to a lot of, see many implementation of HTTP code, no one does not reflect its lightweight features. However, although lightweight, in terms of the amount of code, for a
Create a connection using the Mongoose.connect () methodMongoose.conect (' Mongodb://localhost/myapp ');The above code is linked to the MyApp database of MongoDB via the default port 27017. We can also set some specific parameters for the URL:Mongoose.conect (' Mongodb://username:[email protected]:p ort/databasename?options ... ');OptionsThe Connect method can accept an options objectMongoose.connect (URI, options);Here is the Options key
DB-Set which database to connect to
Server-S
' 1234567890 ' New mongostore url:config.db, ' sessions 'app.routeris the enhanced version of Connect router, which is used to process, and so on, the app.get app.post request processing settings, the corresponding function is called when the browser accesses the corresponding URL in these settings express.router . If it is not explicitly called, app.use(app.router) Express will be app.get(...) implicitly called when the first encounter such a setting, so this can no
If a document has a field of type string array, such as {id:1,tags:[' AA ', ' BB ', ' cc '}, now to change the ' BB ' of the tags field to ' bb ', the previous way is to write:Articlemodel.find ({tags:{$all: [Doc.name]}},function(err,articles) {Articles.foreach (function(article) { for(varj = 0;j){ if(Article.tags[j] = = =doc.name) {Article.tags[j]=Req.body.name; Article.markmodified (' Tags '); Article.save (); Break; }
data, enter the use
gabdb
db.user.insert ({dataid : 10001})
Db.user.find ()
Switch to the From node, you will find that using show DBS will error, because you have not opened the permission, enter Rs.slaveok (), can be successfully accessed. Switch from node
MONGO localhost:10002
//no permission Query
show DBS
//error
2016-01-06t14:48:53.155+0800 E query [ THREAD1] error:listdatabases failed:{"OK": 0, "errmsg": "Not Master and Slaveok=false", "Code": 13435}:
//Open
gabriel:seconda
The specific code looks like this:
var express = require (' Express ');
var mongoose = require (' Mongoose ');
var router = Express. Router ();
var person = Mongoose.model (' person ', {
id:number,
name:string
});
/* Add/*
router.get ('/insert ', function (req, res) {
var student = new Person ({
id:1,
name: "Huop"
});
Mongoose.connect ("Mongodb://localhost:27017/test");
Student.save (funct
(Error,doc) {if (error) {Console.log (error);} else {console.log (doc);}}); Data UpdateLearn the preservation of data, and then we begin to learn to update the data it!1. Example: obj.update (query condition, update object, callback);var conditions = {name: ' Test_update '}; var update = {$set: {age:16}}; Testmodel.update (conditions,
GitHub Address: Https://github.com/linguowei/myblogClone the project Git down;Analysis:# git clone https://github.com/linguowei/myblog.git# cd myblog# npm install# npm run build# CD admin # NPM Run build#. CD.. /# node app.js# localhost:7000# localhost:7000/adminRun the code;Install dependent packages here, as well as package build background projects and foreground projects# node app for running servicesApp.jsWhich is connected to the data:App.use (Router)Database connection + set up various ta
Build the Dumall database, create goods collections, import data files, or manually insert them yourself. MongoDB Installation and Environment building: http://www.cnblogs.com/ccyinghua/p/7887713.html to create a database and insert data, you can enter the MONGO operations database, insert operations in command line form, That is, after the successful start of MongoDB, as an administrator to open a command line window input MONGO, you can do some database operations, you can also download mongov
The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion;
products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the
content of the page makes you feel confusing, please write us an email, we will handle the problem
within 5 days after receiving your email.
If you find any instances of plagiarism from the community, please send an email to:
info-contact@alibabacloud.com
and provide relevant evidence. A staff member will contact you within 5 working days.