简体   繁体   中英

Node JS, How do i get data from a collection with Mongoose

I'm using MVC. How can I use the method findOne({}) at my loginController ?

I just want to get data from my collection. Also that collection is already exist with couple things. All I want, get data from it. By the way I'm sorry for my English.

App.js :

const dbURL = process.env.DB_URL;
mongoose.connect(dbURL, { useNewUrlParser: true, useUnifiedTopology: true, useCreateIndex: true })
        .then((result) => {console.log('bağlandı'); app.listen(8080);})
        .catch((err) => console.log(err))

loginController.js :

const loginControllerPost = async (req, res) => {
        db.collection.findOne({req.body.username}) //How to properly use the method?
}

You need to define schemas (tables) to tell mongoose what database structure look like. For example, UserSchema:

const conn = mongoose.createConnection('your connection string');
const UserSchema = new Schema({
  name: String,
  username: String,
  password: String,
}, {
  collection: 'users', // define collection name here
});
const UserModel = conn.model('UserModel', UserSchema);
const user = await UserModel.findOne({ username: 'Alice' });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM