【发布时间】:2015-09-14 06:31:04
【问题描述】:
我正在编写一个 node.js 应用程序,其中有两个猫鼬模式 Wallet 和 User。
- 我想添加 Wallet 作为对用户的引用 并从 POSTMAN 传递适当的 json。这就像在 OOP 中在另一个类中添加一个类的引用,在 RDBMS 中添加外键概念。
我已经写了这样的模式:
user.js
var mongoose = require('mongoose');
var userSchema = new mongoose.Schema({
userId: {type: String},
isAdmin: {type: Boolean, default: false},
password: {type: String},
name: {type: String},
wallet: {type: mongoose.Schema.Types.ObjectId, ref: 'Wallet'} //see here
});
module.exports = mongoose.model('User', userSchema);
我上面引用钱包的方式对吗?如果没有,你能告诉我正确的方法吗?
wallet.js
var mongoose = require('mongoose');
var walletSchema = new mongoose.Schema({
money: {type: Number, default: 0, min: 0},
});
module.exports = mongoose.model('Wallet', walletSchema);
以下是我的用户路由文件。
userRoute.js
router.route('/user')
.post(function (req, res) {
var user = new User();
user.userId = req.body.userId;
user.password = req.body.password;
user.name = req.body.name;
user.isAdmin = req.body.isAdmin;
user.wallet = req.body.wallet; // see here
user.save(function(err, user){
if(err){
res.json({ message: 'Failure' });
return false;
}
res.json({ message: 'Success' });
});
})
我将钱包分配给用户对象的方式是否正确?如果不是,你能告诉我正确的方法吗?
现在我想从 Postman 发布原始 json。 json 会是什么样子?
【问题讨论】:
标签: javascript node.js mongodb mongoose postman