在后端,我使用的是猫鼬、快递和节点js。我想加入mongodb。如果这是SQL,这并不难。因为我是蒙戈数据库的新手。这对我来说是个问题。在这个平台上,我已经尝试了很多答案,但它们都没有对我的处境有所帮助。
我的数据库中有两个模式。
项目
import mongoose from 'mongoose';
const Schema = mongoose.Schema;
export const item_schema = new Schema({
item_no: {
type: String
},
name: {
type: String
},
item_category: {
type: String
},
no_of_copies: {
type: Number
},
public_or_rare: {
type: String
},
user_no: {
type: String
}
});图书
import mongoose from 'mongoose';
const Schema = mongoose.Schema;
export const book_schema = new Schema({
item_no: {
type: String
},
isbn_no: {
type: String
},
author: {
type: String
},
published_year: {
type: Number
},
publisher: {
type: String
},
book_category: {
type: String
}
});请注意,这些模型中没有错误,因为这些模型与我的API中的其他控制器运行良好。
我希望获得图书和项目表数据作为一个对象,其中图书和项目共享相同的item_no
为了达到我的目标,我尝试了下面的代码,
export const get_books_all_details = (req, res) => {
Book.find({}, (err, book) => {
if (err) {
res.send(err);
}
else {
let my_book = book;
// res.json(my_book);
Item.findOne({ item_no: my_book.item_no }, (err, item) => {
//Item.find({}, (err, item) => {
if (err) {
res.send(err);
}
else {
let my_item = item;
//res.send(my_book+my_item);
res.json({
/* item_no: my_item.item_no,
item_name: my_item.item_name,
item_category: my_item.item_category,
no_of_copies: my_item.no_of_copies,
public_or_rare: my_item.public_or_rare,
isbn_no: my_book.isbn_no,
author: my_book.author,
published_year: my_book.published_year,
publisher: my_book.publisher,
book_category: my_book.book_category , */
book:my_book,
item:my_item
})
}
});
}
});
};在顶部,我使用find()获取所有书籍,如果item表中有与item_no匹配的记录,我也希望获得该特定项。这就是为什么我在find()中使用findOne(),我不知道它是对还是错!
所以这个新来的人等着你们帮忙,真的很感激。如果你能帮助我的代码和解释,这将是伟大的!
发布于 2019-05-04 20:12:16
我想加入mongodb
MongoDB是一个NoSQL数据库,专门为避免连接和强制数据去规范化而构建。如果您需要加入一个文档,请将它放入另一个文档中。如果您像在任何SQL数据库中一样,在MongoDB中构建集合,那么只会有一个不兼容ACID的关系数据库,这是危险的。
https://stackoverflow.com/questions/55986169
复制相似问题