简体   繁体   中英

Return the data of a model directly instead of a dictionary Express.js and Mongoose

Probably the title isn't very clear and is a bit confusing, and to be honest, I do not really know how to ask this question since I'm new to JavaScript and MongoDB, so I'll try to do my best to explain my problem.

Sorry in advance if this is a very basic question or it has already been asked, but since I do not really know how to ask this, I haven't been able to find any answers at all.

I am currently building a REST API using Node.js with Express.js and Mongoose for accessing the server database. I also have a Swift Wrapper and SwiftUI client for working with this data.

In the API, I have the following model:

const UserSchema = new Schema({
  id: { type: String, required: true },
  email: { type: String, unique: true, required: true, lowercase: true },
  displayName: { type: String, required: true },
  displayImage: { type: String, required: true },
  password: { type: String, required: true, select: false },
  dateCreated: { type: Date, default: Date.now() },
  lastLogin: Date,
  collections: [Collection.schema]
}, { collection: 'Usuarios' })

Whose equivalent, in Swift, is the following:

public struct User: Codable, Identifiable {

    // MARK: - STORED PROPERTIES

    /// The account's ID as registered by the server.
    // swiftlint:disable:next identifier_name
    public let id: String

    /**
     The account's email.
     */
    public let email: String

    /**
     The account's display name.
     */
    public let displayName: String

    /**
     The account's display image.
     */
    public let displayImage: String

    /**
     The account's password.
     */
    public let password: String?

    /**
     The date the account was created.
     */
    public let dateCreated: String

    /**
     The date of the last login.
     */
    public let lastLogin: String

    /**
     The collections associated with this account.
     */
    public let collections: [Collection]

}

/// Grants us conformance to `Hashable` for _free_
extension User: Hashable {
    public static func == (lhs: User, rhs: User) -> Bool {
        return lhs.id == rhs.id
    }

    public func hash(into hasher: inout Hasher) {
        hasher.combine(id)
    }
}

Then, I have the following function for retrieving users:

function getUsers (req, res) {
  User.findOne({id: req.userID}, (err, user) => {
    if (err) return res.status(500).send({message: `An error occurred while doing the petition: ${err}`})
    if (!user) return res.status(404).send({message: `No user with id ${req.userID} could be found.`})

    res.send(200, { user })
  }).select('-_id')
}

Until here, everything is alright. If I make a post request to a specific endpoint, the getUsers function is run and I am returned the following data:

{
    "user": {
        "id": "ecd4e343-4898-4daf-aa2b-dd176011a70c",
        "email": "ena.viens@mailtag.com",
        "displayName": "Buck",
        "displayImage": "image",
        "dateCreated": "2022-04-17T22:01:53.960Z",
        "lastLogin": "2022-04-17T22:02:13.115Z",
        "collections":[],
        "__v":0
    }
}

The problem comes when I decode this data into the swift model provided above. Since the API first returns a user dictionary, I cannot decode the data into the model because it throws an error.

How would I make express.js (or mongoose) return directly the data instead of another dict? Is this the correct way to do this, or should I instead change the Swift file where I decode the data so that it expects a dictionary?

Thanks in advance.

I finally found an answer to this question. At the beginning I used @jnpdx 's answer by creating a Container that only had one variable that was the data model that was retrieved. I was using this approach until, after looking for examples of different apis in GitHub, I finally found the solution. It was as simple as using Express.js' res.json function.

This allows to directly send the json data easily.

Sorry for asking this stupid question, and I hope I helped some people out there!

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