簡體   English   中英

如何在 Mongoose 中將一個模式的引用添加到另一個模式並通過 json 插入數據?

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

我正在編寫一個 node.js 應用程序,其中有兩個 mongoose 模式WalletUser

  • 我想添加Wallet 作為對 User 的引用,並從 POSTMAN 傳遞適當的 json。 這就像在 OOP 和 RDBMS 中的外鍵概念中添加一個類的引用。

我已經寫了這樣的模式:

用戶.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);

我上面提到的錢包的方式對嗎? 如果沒有,你能告訴我正確的方法嗎?

錢包.js

var mongoose = require('mongoose');

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

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

以下是我的用戶路由文件。

用戶路由.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...

這個“參考”其實是對貓鼬的更高層次的詮釋。

這就是為什么你不能直接做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;
…

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM