我正在编写一个node.js应用程序,其中有两个 Mongoose 模式钱包和用户。
- 我想添加钱包作为对用户的引用并从 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 会是什么样子?
最佳答案
user.wallet = req.body.wallet
不起作用。
就User
而言,user.wallet
只是一个ObjectId类型的简单字段,它存储一个24个字符的十六进制字符串对象:522abc ...
。
这个“引用”实际上是对 Mongoose 的更高层次的解释。
这就是为什么你不能直接执行user.wallet = req.body.wallet
。你必须做这样的事情:
var user = new User();
…
// user.wallet = req.body.wallet; // won't work
var wallet = new Wallet(req.body.wallet) // because Wallet too is a Schema just like User
user.wallet = wallet.id;
…
关于javascript - 如何在 Mongoose 中将一个模式的引用添加到另一个模式并通过 json 插入数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31087815/