简体   繁体   中英

mongoose router find by reference properety

I am working in my project I already wrote the server.js file for backend this is my mongoose schema and model

const BookSchema = new mongoose.Schema({
title: {
  type: String,
  required: true
},
isbn: {
  type: String,
  required: true
},
author: {
  type: String,
  //required: true
},
description: {
  type: String
},
published_date: {
  type: Date
},
publisher: {
  type: String
},
updated_date: {
  type: Date,
  default: Date.now
}
});

// make data model from schema
const Book = mongoose.model('book', BookSchema);

this is my router

router.get('/:id', (req, res) => {


 Book.findById(req.params.id)
.then(book => res.json(book.title))
.catch(err => res.status(404).json({ nobookfound: 'No Book found' }));
});

How can I pass Book.isbn through get request to get Book.title

just use the findOne method

Book.findOne({isbn:"pass isbn value here"})
.then(book => res.json(book.title))
.catch(err => res.status(404).json({ nobookfound: 'No Book found' }));
});

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