Label:Nodejs operation MongoDB can use Mongoose:Mongoose is a MongoDB object modeling tool designed to work in an asynchronous environment.Install Mongoose:NPM Install MongooseGet MongoDB Connectionvar conn = mongoose.connect (' mongodb://localhost/mytest ');var Schema = Mongoose. Schema, ObjectId = Schema.objectid;var person = new Schema ({Title: {type:string}, age: {type:number, Min:5, max:20}, Meta: {Likes: [String], Birth: {type:date}}});var p = m
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
Schema supports plugins so you can extend some of the featuresThe following example is when document save is customized to update the last modified date of the pluginLastMod.jsmodule.exports = exports = function Lastmodifiedplugin (schema, options) { schema.add ({lastmod:date}) C2/>schema.pre (' Save ', function (next) { this.lastmod = new Date next () }) if (Options Options.index) { schema.path (' Lastmod '). Index (Options.index) }}//game-schema.jsvar lastmod = require ('./ Las
UpdateThere are several ways to update the document. Let's take a look at the traditional Update methodTank.findbyid (ID, function (err, Tank) { if (err) return HandleError (err); Tank.size = "large"; Tank.save (err) { if (err) return HandleError (err); Res.send (tank); });The above code is the first to find out a dociment and then in the update. What if we don't want to find dociment to update directly?Tank.update ({_id:id}, {$set: {size: ' Large '}}, callback
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
Tags: model Mon option. com family uri Add tags div Model.find(query, fields, options, callback) Model.find({ ‘some.value‘: 5 }, function (err, docs) {
// docs is an array
}); Model.findoneModel.findOne({ age: 5}, function (err, doc){
// doc is a Document
}); Model.findbyidModel.findById(obj._id, function (err, doc){
// doc is a Document
}); Model.countModel.count(conditions, callback); Model.removeModel.remove(conditions, callback); Model.distinctModel.distinct(field, condition
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
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; }
Recently developed too busy, there is no time to update the blog, want to use this blog to summarize the relevant experience, in case the following can be used:First, Antd1.onChange of undefined problem: it is possible that the form in the page has the same name, or the parent element of the time-out form does not have a unique key set.Wait for update ...Second, ES6Wait for update ...Third, Mongoose1. When querying, if you encounter an association relationship that queries multiple tables, you c
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
Go to the Bin folder under the folder where MongoDB is installed, execute the command: MONGO, you can use MongoDB.After installing the mongoose, in App.js, first introduce mongoose this module:var mongoose = require (' Mongoose ');Connect to the corresponding database;Port number default link 27017;Test is the name of
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
In the recent study of Nodejs, here are some APIs that use mongoose to manipulate MongoDB.
Prelude:
1. Installation of Mongoose:var Mongoose = require (' Mongoose ');
2. Connecting Mongodb:mongoose.connect (' Mongodb://localhost/nodejs ');
3. CREATE TABLE structure, field: var Schema = MongoDB. Schema;var Movieschema = new Schema ({title:string,content:string,})
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.