8

I'm having trouble trying understand which is the collection I'm saving the document to. I have the following piece of code:

var message = mongoose.Schema({
    created: {type: Date, default: Date.now}
});

var message_temp = mongoose.model('message', message);

Now what can I do to save that message to a specific collection? If I do

 message.save(function(err){});

Where is the message actually kept?

extremeMeta
  • 93
  • 1
  • 1
  • 7

3 Answers3

13

To define a collection you just need to:

var message_temp = mongoose.model('message', message,'collectionyouwant');
ɐlǝx
  • 1,384
  • 2
  • 17
  • 22
  • Doesn't work for me: OverwriteModelError: Cannot overwrite `message` model once compiled. The question as I see was about temporary (dynamic) sending request to db to specific collection – nick Sep 01 '19 at 13:28
  • Being March 2020 this is not in the mongoose docs, unbelievable... Thanks for the answer works with mongoose 5.9.6 – Rodrigo Mar 24 '20 at 22:05
  • Not sure since when it was there, but as of March 2021 this is the [model documentation](https://mongoosejs.com/docs/api/mongoose.html#mongoose_Mongoose-model). Good catch though. – Luca Fagioli Mar 09 '21 at 14:33
4

Im six years late, but some people might still find this useful. Per docs, you specify the collection like this when saving a model, { collection: 'name' }

Like this:

 const model = new Model({
        _id: new mongoose.Types.ObjectId(),
        somefield: "some value",
        someotherfield: "some other value"
    }, { collection: 'here you put the name of your collection' });

link to docs https://mongoosejs.com/docs/guide.html#collection

Juan Herrera
  • 63
  • 1
  • 7
0

i think this will help you

creating collection schema and collection

// creating schema(bluepring) for collection(table)

const userSchema = {
    email: String,
    password: String
};
//creating collection of schema
const User = mongoose.model("User", userSchema);

creating object document to store in collection

const newUser = new User({//newUser is the document object we want to store
            email: req.body.username,
            password: req.body.password
        });

saving document into collection

 newUser.save(function(err){
            if(err){
                console.error(err);
            }
            else{
                console.log("data added successfully");
                
            }
        });

hope you like it if there is something wrong in my explaination and code than please point it out