[英]How to link MongoDB collections
i am beginner, being fighting with that case already 3 days, please help.我是初学者,已经与那个案子打架了3天,请帮忙。 Using Node js and Mongoose.使用节点 js 和 Mongoose。
I have users, every user make $ on exact website.我有用户,每个用户都在确切的网站上赚钱。
How correctly represent code in Controller to create new User and then retrieve all users + salary?如何正确表示 Controller 中的代码以创建新用户然后检索所有用户 + 工资?
User Schema:用户架构:
const mongoose = require('mongoose')
const Schema = mongoose.Schema
const userSchema = new Schema({
username :{
type: String,
},
website: {
sitename: {
type :String
},
income: [{
type: Schema.Types.ObjectId,
ref : 'Income'
}],
incomeDate: {
date: Date,
default: Date.now
}
},
})
module.exports = mongoose.model('User', userSchema)
Income Schema:收入模式:
const mongoose = require('mongoose')
const Schema = mongoose.Schema
const incomeSchema = new Schema({
income: {
type: Number
},
user: {
type: Schema.Types.ObjectId,
ref : 'User'
}
})
module.exports = mongoose.model('Income' , incomeSchema)
Controller: Controller:
const User = require('../models/user.model')
const Income = require('../models/income.model')
module.exports.createUser= async function(req, res){
try{
const newUser = await new User({})
// How to create user with link to Salary?
res.status(200).json(newUser )
}catch{}
}
module.exports.getUsers = async function(req, res){
try{
const getAll = await User.find()
// How to get users with Salary?
res.status(200).json(getAll )
}catch{}
}
Routes:路线:
router.post('/new' , controller.createUser)
router.get('/all', controller.getUsers)
Why don't you put income as a field under the user schema but instead create a new collection for it?为什么不将收入作为用户模式下的字段,而是为它创建一个新集合?
Update:更新:
MongoDB populate has always been a confusing feature while the documentation is not doing a very good job explaining it. MongoDB 填充一直是一个令人困惑的功能,而文档并没有很好地解释它。
So basically when you are creating a new user document, you should store the "id" of the income doc.所以基本上当你创建一个新的用户文档时,你应该存储收入文档的“id”。 into the income field.进入收入领域。 That's essentially what type: Schema.Types.ObjectId
means.这本质上就是type: Schema.Types.ObjectId
的意思。 When you're getting the user document, you should call .populate('website.income')
which will then populate the income field.当您获取用户文档时,您应该调用.populate('website.income')
来填充收入字段。 After the population happened, the income document will basically become an embedded document within the user document.人口发生后,收入文件基本上会成为用户文件中的嵌入文件。
So if you still want to have income in a separate collection, with some changes, your code should be like the following:因此,如果您仍然希望在单独的集合中获得收入,并进行一些更改,您的代码应该如下所示:
//User Model file
const mongoose = require('mongoose')
const Schema = mongoose.Schema
const userSchema = new Schema({
username: {
type: String,
},
website: {
sitename: {
type: String
},
//Remove the array bracket []
income: {
type: Schema.Types.ObjectId,
ref: 'Income'
},
incomeDate: {
date: Date,
//add missing ()
default: Date.now()
}
},
});
//You don't need exports for schemas
mongoose.model('User', userSchema)
//Income model file
const mongoose = require('mongoose')
const Schema = mongoose.Schema
const incomeSchema = new Schema({
income: {
type: Number
},
//No need of ref to the user collection.
//Plus if you can't really have two doc referencing one another is this way,
//there is going to be a problem regarding which one should be created first.
//Even if the above problem is solved. You will still need to run a update
//operation to populate the first document created with the id of the 2nd document
});
//You don't need exports for schemas
mongoose.model('Income', incomeSchema)
//The controller file
//Dependency
const mongoose = require('mongoose');
//Connect to the DB
const options={
useNewUrlParser: true,
useUnifiedTopology: true,
useFindAndModify: false
}
const db = mongoose.createConnection('url', options);
db
.once('open', () => dblog.info('DB Connected'))
.catch(err => dblog.error('Error Connecting to DB' + ' ' + err));
//Load the models
require('../models/user.model');
require('../models/income.model');
const userBD = db.model('User');
const incomeDB = db.model('Income');
//Create new income doc.
module.exports.createIncome = (req, res) => {
const income = {
income: 2000,
};
new incomeDB(income)
.save()
.then(() => res.json({ msg: 'Income Doc. Updated / Created' }))
.catch(err => {
console.log(err);
res.json({ msg: 'Error Updating / Creating Income Doc.' });
})
};
//Create new user doc.
module.exports.createUser = (req, res) => {
//Query the income db
incomeDB.find({ income: 2000 })
.then(income => {
//Create the user object to be stored
const newUser = {
//Assuming you get the information from a html form of some sort
username: req.body.userName,
website: {
sitename: req.body.siteName,
//In order to use .populate() you have to store the id of the income doc here
income: income._id,
},
};
//Save the user object into the user db
new userBD(newUser)
.save()
.then(() => res.json({ msg: 'New User Created' }))
.catch(err => {
console.log(err);
res.json({ msg: 'Error Creating New User' });
});
})
.catch(err => {
console.log(err);
res.json({ msg: 'Error Querying Income DB' });
});
};
//Get user doc.
module.exports.getUser = (req, res) => {
//Query the user db using user name for example
userBD.find({ username: 'StackOverflow Admin' })
//Populate the income field in the website object
.populate('website.income')
//Pass the user data into the response
.then(userData => res.json(userData))
.catch(err => {
console.log(err);
res.json('Error Looking Up DB');
});
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.