簡體   English   中英

貓鼬一對多

[英]Mongoose one-to-many

你能解釋一下如何組織mongoose模型來創建一對多的連接嗎? 需要保留單獨的集合。

假設我有商店和商品

//store.js

var mongoose = require('mongoose');

module.exports = mongoose.model('Store', {
    name : String,
    itemsinstore: [ String]
});

//item.js

var mongoose = require('mongoose');
module.exports = mongoose.model('Item', {
    name : String,
    storeforitem: [String]
 });

我是以正確的方式做到的嗎?

以及如何訪問傳遞數據到arryas? 這是代碼輸入項目的名稱。 但是如何輸入id到id的數組(itemsinstore)?

app.post('/api/stores', function(req, res) {
    Store.create({
        name: req.body.name,
    }, function(err, store) {
        if (err)
            res.send(err);
    });
})

您應該使用模型引用和populate()方法: http//mongoosejs.com/docs/populate.html

定義模型:

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var storeSchema = Schema({
   name : String,
   itemsInStore: [{ type: Schema.Types.ObjectId, ref: 'Item' }]
});
var Store = mongoose.model('Store', storeSchema);

var itemSchema = Schema({
    name : String,
    storeForItem: [{ type: Schema.Types.ObjectId, ref: 'Store' }]
});
var Item = mongoose.model('Item', itemSchema);

將新項目保存到現有商店:

var item = new Item({name: 'Foo'});
item.save(function(err) {

  store.itemsInStore.push(item);
  store.save(function(err) {
    // todo
  });
});

從商店獲取商品

Store
  .find({}) // all
  .populate('itemsInStore')
  .exec(function (err, stores) {
    if (err) return handleError(err);

    // Stores with items
});

您可以使用Virtuals的最佳實踐。

Store.js

const mongoose = require('mongoose')
const Schema = mongoose.Schema

const StoreSchema = new Schema({
    name: {
        type: String,
        required: true
    },
    createdAt: {
        type: Date,
        default: Date.now
    }
})

StoreSchema.virtual('items', {
    ref: 'Item',
    localField: '_id',
    foreignField: 'storeId',
    justOne: false // set true for one-to-one relationship
})

module.exports = mongoose.model('Store', StoreSchema)

Item.js

const mongoose = require('mongoose')
const Schema = mongoose.Schema

const ItemSchema = new Schema({
    storeId: {
        type: Schema.Types.ObjectId,
        required: true
    },
    name: {
        type: String,
        required: true
    },
    createdAt: {
        type: Date,
        default: Date.now
    }
})

module.exports = mongoose.model('Item', ItemSchema)

StoreController.js

const Store = require('Store.js')

module.exports.getStore = (req, res) => {
    const query = Store.findById(req.params.id).populate('items')

    query.exec((err, store) => {
        return res.status(200).json({ store, items: store.items })
    })
}

請記住,默認情況下,虛擬機不包含在toJSON()輸出中。 如果要在使用依賴於JSON.stringify()函數JSON.stringify()res.json() 函數 JSON.stringify()時顯示填充虛擬,請在架構的toJSON選項上設置virtuals: true選項。

// Set `virtuals: true` so `res.json()` works
const StoreSchema = new Schema({
    name: String
}, { toJSON: { virtuals: true } });

好的,這是你定義依賴的方式:

var mongoose = require('mongoose');

module.exports = mongoose.model('Todo', {
    name : String,
    itemsinstore: [{ type: Schema.Types.ObjectId, ref: 'Item' }]
});

並確保您有不同的名稱:

var mongoose = require('mongoose');
module.exports = mongoose.model('Item', {
    name : String,
    storeforitem: [String]
 });

在這兩種情況下都要關注Item

然后你只想傳遞ObjectIDs數組。 在此處查看更多信息: http//mongoosejs.com/docs/populate.html

嘗試這個:

 Store.findOne({_id:'5892b603986f7a419c1add07'})
  .exec (function(err, store){
    if(err) return res.send(err);

   var item = new Item({name: 'Foo'});
   item.save(function(err) {

   store.itemsInStore.push(item);
   store.save(function(err) {
    // todo
 });
});

暫無
暫無

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

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