简体   繁体   English

如何在 Mongoose 中将一个模式的引用添加到另一个模式并通过 json 插入数据?

[英]How to add reference of one schema to another in Mongoose and inserting data by json?

I am writing a node.js app where I have two mongoose schemas Wallet and User .我正在编写一个 node.js 应用程序,其中有两个 mongoose 模式WalletUser

  • I want to add Wallet as a reference to User and pass the appropiate json from POSTMAN.我想添加Wallet 作为对 User 的引用,并从 POSTMAN 传递适当的 json。 This is like adding a reference of one class in another in OOPs and foreign key concept in RDBMS.这就像在 OOP 和 RDBMS 中的外键概念中添加一个类的引用。

I have written the schemas like this:我已经写了这样的模式:

user.js用户.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);

Is the way I referenced wallet above, correct?我上面提到的钱包的方式对吗? If not, can you tell me the right way?如果没有,你能告诉我正确的方法吗?

wallet.js钱包.js

var mongoose = require('mongoose');

var walletSchema = new mongoose.Schema({
    money: {type: Number, default: 0, min: 0},  
});

module.exports = mongoose.model('Wallet', walletSchema);

The following is my user route file.以下是我的用户路由文件。

userRoute.js用户路由.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' });
    });     
})

Is the way I have assigned wallet to the user object correct?我将钱包分配给用户对象的方式是否正确? If not can you tell me the right way?如果没有,你能告诉我正确的方法吗?

Now I want to post raw json from Postman.现在我想从 Postman 发布原始 json。 What will the json look like? json 会是什么样子?

user.wallet = req.body.wallet won't work. user.wallet = req.body.wallet不起作用。

As far as User is concerned user.wallet is just a simple field of the type ObjectId that store a 24 char hex string-like object: 522abc... .User而言, user.wallet只是一个 ObjectId 类型的简单字段,它存储一个 24 个字符的十六进制字符串对象: 522abc...

This "reference" is actually a higher level interpretation of Mongoose.这个“参考”其实是对猫鼬的更高层次的诠释。

That's why you can't directly do user.wallet = req.body.wallet .这就是为什么你不能直接做user.wallet = req.body.wallet You have to do something like this:你必须做这样的事情:

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;
…

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM