简体   繁体   中英

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 .

  • I want to add Wallet as a reference to User and pass the appropiate json from POSTMAN. This is like adding a reference of one class in another in OOPs and foreign key concept in RDBMS.

I have written the schemas like this:

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

Is the way I referenced wallet above, correct? If not, can you tell me the right way?

wallet.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

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. What will the json look like?

user.wallet = req.body.wallet won't work.

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... .

This "reference" is actually a higher level interpretation of Mongoose.

That's why you can't directly do 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;
…

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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