Node.js is a JavaScript running environment built on the Chrome V8 engine, which allows JavaScript code to run on the server side. It is very common to perform addition, deletion and modification operations in Node.js. This article will introduce how to use Node.js to perform addition, deletion and modification operations.
1. Add data
To add data in Node.js, you need to use a database module. Commonly used ones include Mongoose, Sequelize, etc. This article uses Mongoose as an example to introduce.
Run the following command in the command line to install:
npm install mongoose --save
First you need to connect to the MongoDB database, the code is as follows:
const mongoose = require('mongoose'); mongoose.connect('mongodb://localhost/test', { useNewUrlParser: true, useUnifiedTopology: true });
Among them,mongodb://localhost/test
means connecting to the local MongoDB database named test.
To use Mongoose, you need to define the data model first. You can create auser.js# in the
modelsfolder. ## file, the code is as follows:
const mongoose = require('mongoose'); const userSchema = new mongoose.Schema({ name: String, age: Number }); module.exports = mongoose.model('User', userSchema);
userSchemadefines the user's name and age attributes.
const User = require('./models/user'); const user = new User({ name: 'John', age: 25 }); user.save((err) => { if (err) { console.log(err); } else { console.log('User created'); } });
user.save()Save the newly added user data to the MongoDB database.
const User = require('./models/user'); User.deleteOne({ name: 'John' }, (err) => { if (err) { console.log(err); } else { console.log('User deleted'); } });
User.deleteOne()means to delete the data whose
nameis
Johnin the user attribute.
const User = require('./models/user'); User.findOneAndUpdate({ name: 'John' }, { age: 26 }, (err, user) => { if (err) { console.log(err); } else { console.log('User updated'); } });
User.findOneAndUpdate()means to find the data whose
nameis
Johnin the user attribute, and modify the
ageattribute to
26.
The above is the detailed content of nodejs addition, deletion and modification. For more information, please follow other related articles on the PHP Chinese website!