如何使用 Mongoose 从 MongoDB 读取数据?
How do I read data from MongoDB using Mongoose?
在 MongoDB 文档中 here 它说要做这样的事情:
db.bios.find()
在我的代码中有这部分:
mongoose.connect('mongodb://localhost:27017/eBookStore');
let newBookSchema = new mongoose.Schema({
bookName: {type: String},
bookSubtitle: {type: String},
publicationDate: {type: Number, default: new Date().getTime()}
});
let Book = mongoose.model('books', newBookSchema);
db.Book.find();
其中 'eBookStore' 是我的数据库名称,'books' 是我的 collection 名称。我知道我在 'db.Book.find()' 中输入 'db' 的地方不正确,但我不知道引用数据库时那里的代码应该是什么样子。请帮忙!
你可以参考mongoose的文档
https://mongoosejs.com/docs/guide.html
具体型号使用下面的 link
https://mongoosejs.com/docs/models.html
例如
让 Book = mongoose.model('Book', newBookSchema,'books');
//第一个参数是 mongoose model name,第二个 schema 和第三个 collection in mongodb
Book.find({}}, 函数(err, arr) {});
使用相同的代码,通过 mongoose 连接 mongo 后,您可以直接进行搜索,无需提及数据库。如果您有要在其中搜索的集合的架构,这总是有效的。
mongoose.connect('mongodb://localhost:27017/eBookStore');
let newBookSchema = new mongoose.Schema({
bookName: {type: String},
bookSubtitle: {type: String},
publicationDate: {type: Number, default: new Date().getTime()}
});
let Book = mongoose.model('book', newBookSchema);
Book.find({queryForFilters});
请注意,我删除了您代码第 9 行中的 's' in books。这是因为 mongoose 以复数 ang 小写表示第一个参数,因此将 book 作为第一个参数传递将导致名为 books 的集合。
mongoose.connect('mongodb://localhost:27017/eBookStore',{useNewUrlParser:true});
//Schema model
let newBookSchema = new mongoose.Schema({
bookName: {type: String},
bookSubtitle: {type: String},
publicationDate: {type: Number, default: new Date().getTime()} // i will have used new Date() only for future data query based on date
});
let Book = mongoose.model('Book', newBookSchema); // Capital letter will be better for distinguish from a normal variable and to remember easly
假设您想查看或 "read" 具有特定 ID 的特定书籍,为此您可以创建一个路由器并读取数据。
app.get('/view/:id', (req, res) => {
var bookId = req.params.id;
//read the data part
Book.findOne({ _id: bookId }, (err, oneBook) => {
if (err) console.error(err);
//pass data to the template engine
res.render('book/sale', { oneBook });
});
// Or you can use findById()
Book.findById({ bookId }, (err, oneBook) => {
if (err) console.error(err);
//pass data to the template engine
res.render('book/sale', { oneBook });
});
});
如果你想得到所有的书:
app.get('/allbooks', (req, res) => {
//find all books
Book.find({}, (err, allBooks) => {
if (err) console.error(err);
res.render('book/list', {allBooks})
})
});
假设您希望通过使用带有操作“/daterange”和方法 POST
的表单来获取用户从 html 模板中选择的两个日期之间的书籍
app.post('/daterange', (req, res) => {
//date input from template engine named start
var startDate = new Date(req.body.start);
//date input from template engine named end
var endDate = new Date(req.body.end);
Book.find({ "publicationDate": { "$gte": startDate, "$lte": endDate } }, (err, booksByDate) => {
var startDate = new Date(req.body.start); // this is why you should use new Date() only for query simplicity
var endDate = new Date(req.body.end);
if (err) console.error(err);
res.render('book/bookbydate', { booksByDate});
});
});
假设你想要最新的书:同样的原则
Book.findOne().sort({ publicationDate: -1 }).limit(1).exec((err, oneBook) => {
if (err) console.error(err);
//or do wahtever with you like with this oneBook
}
如果你想得到倒数第二个
Book.find({}).limit(2).sort({ "_id": -1 }).exec((err, bookSecondLatest) => {
if (err) console.error(err);
// do what ever you want
});
按书名搜索
Book.findOne({bookName: 'Game of thrones'}, (err,oneBook) =>{
console.log(oneBook);
});
You are having this is your schema
1. bookName
2. bookSubtitle
3. publicationDate
So with using any of the you can find the schema details
You have create the function like below to search the book schema from anywhere
public getBookDetails(name, callback: CallableFunction) {
Book.find({bookName: name }, (err, book) => {
if (err) {
callback(err);
} else {
callback(book);
}
});
}
在 MongoDB 文档中 here 它说要做这样的事情:
db.bios.find()
在我的代码中有这部分:
mongoose.connect('mongodb://localhost:27017/eBookStore');
let newBookSchema = new mongoose.Schema({
bookName: {type: String},
bookSubtitle: {type: String},
publicationDate: {type: Number, default: new Date().getTime()}
});
let Book = mongoose.model('books', newBookSchema);
db.Book.find();
其中 'eBookStore' 是我的数据库名称,'books' 是我的 collection 名称。我知道我在 'db.Book.find()' 中输入 'db' 的地方不正确,但我不知道引用数据库时那里的代码应该是什么样子。请帮忙!
你可以参考mongoose的文档
https://mongoosejs.com/docs/guide.html
具体型号使用下面的 link https://mongoosejs.com/docs/models.html
例如 让 Book = mongoose.model('Book', newBookSchema,'books');
//第一个参数是 mongoose model name,第二个 schema 和第三个 collection in mongodb
Book.find({}}, 函数(err, arr) {});
使用相同的代码,通过 mongoose 连接 mongo 后,您可以直接进行搜索,无需提及数据库。如果您有要在其中搜索的集合的架构,这总是有效的。
mongoose.connect('mongodb://localhost:27017/eBookStore');
let newBookSchema = new mongoose.Schema({
bookName: {type: String},
bookSubtitle: {type: String},
publicationDate: {type: Number, default: new Date().getTime()}
});
let Book = mongoose.model('book', newBookSchema);
Book.find({queryForFilters});
请注意,我删除了您代码第 9 行中的 's' in books。这是因为 mongoose 以复数 ang 小写表示第一个参数,因此将 book 作为第一个参数传递将导致名为 books 的集合。
mongoose.connect('mongodb://localhost:27017/eBookStore',{useNewUrlParser:true});
//Schema model
let newBookSchema = new mongoose.Schema({
bookName: {type: String},
bookSubtitle: {type: String},
publicationDate: {type: Number, default: new Date().getTime()} // i will have used new Date() only for future data query based on date
});
let Book = mongoose.model('Book', newBookSchema); // Capital letter will be better for distinguish from a normal variable and to remember easly
假设您想查看或 "read" 具有特定 ID 的特定书籍,为此您可以创建一个路由器并读取数据。
app.get('/view/:id', (req, res) => {
var bookId = req.params.id;
//read the data part
Book.findOne({ _id: bookId }, (err, oneBook) => {
if (err) console.error(err);
//pass data to the template engine
res.render('book/sale', { oneBook });
});
// Or you can use findById()
Book.findById({ bookId }, (err, oneBook) => {
if (err) console.error(err);
//pass data to the template engine
res.render('book/sale', { oneBook });
});
});
如果你想得到所有的书:
app.get('/allbooks', (req, res) => {
//find all books
Book.find({}, (err, allBooks) => {
if (err) console.error(err);
res.render('book/list', {allBooks})
})
});
假设您希望通过使用带有操作“/daterange”和方法 POST
的表单来获取用户从 html 模板中选择的两个日期之间的书籍app.post('/daterange', (req, res) => {
//date input from template engine named start
var startDate = new Date(req.body.start);
//date input from template engine named end
var endDate = new Date(req.body.end);
Book.find({ "publicationDate": { "$gte": startDate, "$lte": endDate } }, (err, booksByDate) => {
var startDate = new Date(req.body.start); // this is why you should use new Date() only for query simplicity
var endDate = new Date(req.body.end);
if (err) console.error(err);
res.render('book/bookbydate', { booksByDate});
});
});
假设你想要最新的书:同样的原则
Book.findOne().sort({ publicationDate: -1 }).limit(1).exec((err, oneBook) => {
if (err) console.error(err);
//or do wahtever with you like with this oneBook
}
如果你想得到倒数第二个
Book.find({}).limit(2).sort({ "_id": -1 }).exec((err, bookSecondLatest) => {
if (err) console.error(err);
// do what ever you want
});
按书名搜索
Book.findOne({bookName: 'Game of thrones'}, (err,oneBook) =>{
console.log(oneBook);
});
You are having this is your schema 1. bookName 2. bookSubtitle 3. publicationDate So with using any of the you can find the schema details
You have create the function like below to search the book schema from anywhere
public getBookDetails(name, callback: CallableFunction) {
Book.find({bookName: name }, (err, book) => {
if (err) {
callback(err);
} else {
callback(book);
}
});
}