【问题标题】:Collection name auto convert to plural in reactjs and mogoDB? [duplicate]集合名称在反应js和mongoDB中自动转换为复数? [复制]
【发布时间】:2019-01-20 10:43:42
【问题描述】:

我想创建集合名称的“派对”和一个请求 getAll 数据。我的模型:

const mongoose = require('mongoose');
let PartySchema = new mongoose.Schema(
    {
        partyId: String,
        partyName: String,
    }
);

module.exports = mongoose.model('Party', PartySchema)

还有我的控制器:

const Party = require('./../models/Party')
module.exports = {
    getAll: (req, res, next) => {
        console.log(Party.find());
        Party.find().exec((err, party)=> {
            if (err)
                res.send(err)
            else if (!party)
                res.send(404)
            else
                res.send(party)
            next()            
        })
    },
}

Console.log 告诉我 collectionName 是“party”而不是“party”。听着怎么了?

【问题讨论】:

    标签: node.js mongodb reactjs


    【解决方案1】:

    mongoose 尝试通过将你的 shema 设为复数形式来推断集合名称。

    但是,您可以使用second parameter 强制您的集合名称:

    let PartySchema = new mongoose.Schema(
        {
            partyId: String,
            partyName: String,
        }, 
        { collection: 'your_collection_name' } 
    );
    

    【讨论】:

    • Cảmơn a @Mạnh Quyết nha, e mới học nên vụ này gà quá, mong a giúp đỡ thêm :)
    • 欢迎 :D~~
    • Anh @Mạnh Quyết, Em hỏi chút, em đang thắc mắc luồng data như sau: 组件导入 các 动作, sau đó 客户端 có các 事件 gọi tới 动作 của em。 Actions sẽ trả về object và dispatch một type nào đó để gọi reducer update state của 组件。 Tuy nhiên em lại chưa tìm thấy nó update cho Component nào hay là chính component phát sinh event client phía trên ạ ? tks a nhé!
    • 我不知道反应:D anh không rành react đâu em
    • ồ, tks a nhé, e tưởng a rành vụ này :)
    【解决方案2】:

    Mongoose 通过一个函数遍历所有集合名称,该函数使用名为toCollectionName 的 fn 将集合名称复数。你可以在这里看到实现:https://github.com/Automattic/mongoose/blob/master/lib/utils.js#L31

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-05-18
      • 2021-01-28
      • 2020-11-23
      • 1970-01-01
      • 2014-09-22
      • 1970-01-01
      • 2018-10-08
      • 2020-02-13
      相关资源
      最近更新 更多