首页 文章

Mongoose填充非规范化数据

提问于
浏览
0

我有 User 型号和 Book 型号 . 我希望我的书中的一些数据在每个 User 文档上进行非规范化,但是如果需要,仍然可以选择填充 . 如果我在 books.$._id 上设置了 ref: 'Book' ,它将填充在 _id 路径内,这是无意的 . 我希望人口覆盖非规范化数据 .

我该如何做到这一点?

users.model.js

const { Schema } = require('mongoose');

const UserSchema = new Schema({
    name: String,
    books: {
        type: [
            {
                _id: Schema.Types.ObjectId,
                title: String,
                length: Number,
            },
        ],
        default: [],
    },
});

Desired outcome

users.controller.js

app.get('/', async (req, res, next) => {
    const users = await User.find({})
    /*
    users: [{
        _id: ObjectId(),
        name: 'Andrew',
        books: [{
            _id: ObjectId(),
            title: 'Game of Thrones',
            length: 298,
        }, { ... }],
    }, { ... }]
    */
});

app.get('/:id', async (req, res, next) => {
    const book_id = req.params.id;
    const user = await User.findById(book_id).populate({
        path: 'books',
        model: 'Book',
    });
    /*
    user: {
        _id: ObjectId(),
        name: 'Andrew',
        books: [{
            _id: ObjectId(),
            name: 'Game of Thrones',
            length: 298,
            author: 'Simone Dunow',
            releasedOn: Date(),
            price: 30,
            ...
        }, { ... }],
    }
    */
});

架构我到目前为止尝试过:

books: {
        type: [
            {
                _id: Schema.Types.ObjectId,
                title: String,
                length: Number,
            },
        ],
        default: [],
        ref: 'Book',
    },

返回 { _id: null } 的数组

books: {
        type: [
            {
                _id: {
                    type: Schema.Types.ObjectId,
                    ref: 'Book',
                },
                title: String,
                length: Number,
            },
        ],
        default: [],
    },

书籍填充在 _id 内: { _id: { Book } }

books: {
        type: [
            {
                type: {
                    _id: Schema.Types.ObjectId,
                    title: String,
                    length: Number,
                },
                ref: 'Book',
            },
        ],
        default: [],
    },

抛出异常:类型无效

1 回答

  • 0
    const UserSchema = new Schema({
        name: String,
        books: [{
            id: { type : Schema.Types.ObjectId, ref : 'Book'} //Whatever string you have used while modeling your schema
            title: String,
            length: Number,
        }],
    });
    

    使用架构时,您可以填充如下:

    populate({ path: 'books.id' })
    

    输出:

    { 
        _id : // someid
        name : "somename"
        books : [
            { 
              id : {//document referring to Books collection},
              title : "sometitle",
              length : //somelength
            }, ...
        ]
    }
    

相关问题