Mongoose doesn't save data to the MongoDB

前端 未结 3 887
情歌与酒
情歌与酒 2021-02-04 18:02


Below is an object literal I am trying to save to MongoDB. It is defined within the app.js file which is an Express server. As the object is hardcoded within the server, my

3条回答
  •  被撕碎了的回忆
    2021-02-04 18:30

    My code was different, but my result was apparently the same: Apparently, I wasn't saving to Mongo despite the .save call. HOWEVER, the save was actually taking place, I just didn't realize what some of the Mongoose parameters mean, and that it takes some liberties forming your collection name.

    More specifically, when you use:

    mongoose.model('MyModelName', invitationSchema);
    

    to form your collection name, your model name gets converted to lower case and an "s" gets appended (if not there). See also http://samwize.com/2014/03/07/what-mongoose-never-explain-to-you-on-case-sentivity/

    You can, if you want, bypass these collection naming conventions to some extent by using a collection name parameter when you create the schema. See http://mongoosejs.com/docs/guide.html#collection

    Here's mine:

    const modelName = "SharingInvitation";
    const collectionName = modelName + "s";
    
    const numberOfHoursBeforeExpiry = 24;
    
    var expiryDate = new Date ();
    expiryDate.setHours(expiryDate.getHours() + numberOfHoursBeforeExpiry);
    
    var invitationSchema = new Schema({
        // _id: (ObjectId), // Uniquely identifies the invitation (autocreated by Mongo)
    
        // gives time/day that the invitation will expire
        expiry: { type: Date, default: expiryDate },
    
        // The user is being invited to share the following:
        owningUser: ObjectId, // The _id of a PSUserCredentials object.
        capabilities: [String] // capability names
    }, { collection: collectionName });
    

提交回复
热议问题