I have an array models with all the model names in my project. I get any of the model name in request.params.model. I also get some data in request.body. Now all I wanted to do is insert the data received into the collection pointed by request.params.model. How can I achieve this?
I used model method of mongoose to achieve this. Below is a sample mongoose query.
require("mongoose").model(req.params.model).create(req.body, function(err, doc) {
res.json(doc);
});
Related
I am attempting a CRUD app with MEAN stack. I am using mongoose in Express to call to the MongoDB. I am using the FindOne function with a specified parameter, and it's always returning the same (incorrect) document.
I know I am connected to the correct database, since I get a document back from that collection, but it's always the same document, no matter what I pass as the parameter.
module.exports = mongoose.model('Player', playersSchema, 'players'); //in player.js
const Player = require('./model/players');
app.get('/api/player/:id', (req, res) =>{
Player.findOne({id: req.params.playerId},
function(err, player) {
if(err) {
res.json(err);
}
else {
res.json(player);
}
});
});
I have 3 separate "players", with three distinct "playerID" fields (38187361, 35167321, 95821442). I can use Postman to GET the following URL, for example:
http://localhost:3000/api/player/anythingyouWantInHere
and it will return 38187361, the first document. I've been over this website, many tutorials, and the Mongoose documentation and I can't see what I'm doing wrong..
I'd like to eventually find by playerId OR username OR email, but one hurdle at a time...
From the mongoose documentation of findOne, if you pass Id a null or an empty value, it will query db.players.findOne({}) internally which will return first document of the collection everytime you fetch. So make sure you are passing non-empty id here.
Note: conditions is optional, and if conditions is null or undefined,
mongoose will send an empty findOne command to MongoDB, which will
return an arbitrary document. If you're querying by _id, use
findById() instead.
Your route is '/api/player/:id', so the key on the req.params object will be 'id' not 'playerId'.
I don't know what/where/if you're populating the playerId param, but if you update your query to call req.params.id it should actually change the document based on the path as you seem to be wanting to do.
I had the same problem, and it was that the name of column's table was different from the model I had created.
In my model the name of the wrong column was "role" and in my table it was "rol".
I want to validate some inner elements of an object against schemas that are members of a larger schema before posting that object on the model correspondent to that larger schema.
Someone already asked this question and this answer has something similar on the second option proposed:
var p = new People({
name: 'you',
age: 3
});
p.validate(function(err) {
if (err)
console.log(err);
else
console.log('pass validate');
});
The problem is that before doing the validation one has to create a new model with var People = mongoose.model('People', peopleSchema);.
Does this mean in this case that a new collection 'People' will be stored in the MongoDB database?
Is the act of calling mongoose.model('People', peopleSchema); altering the database in any way?
If so, is there a way to do this validation without creating a new collection, in this case 'People'?
The schema I want to validate will be stored as a component of another document already in the database and I don't want to pollute the database with unused collections.
I need to change the collection based on model data in mongoose. I am tapping into the pre save event:
mySchema.pre('save', function (next) {
this.schema.set('collection', getCollectionName(this.dt));
next();
});
But that seems to have no effect on the save destination. Those collections seemed to be set in the mongoose model already. Any ideas on where I might be able to set this after the model has been created?
When I do the .find operation like the following:
Collection.find({name: 'Erik'}, function (err, docs) {
// do momething
});
'docs' variable is populated with an array of fully functional mongoose documents. But I need to get an array of pure JSON objects.
I know I can loop through the 'docs' array by forEach and get an objects by using .toJSON() method. Does mongoose support the feature, I'm interested?
If you're using Mongoose 3.x you can use the lean query option to do this:
Collection.find({name: 'Erik'}).lean().exec(function (err, docs) {
// docs are plain javascript objects instead of model instances
});
.exec(function(err, docs){
docs= docs.map(o => o.toObject());
This will include virtuals and getters
Map through results and convert each to JS object:
const result = await model.find({some: 'query'});
return result.map((r) => r.toObject());
I know I have to define Schema's in Mongoose, but I have a case where I'm connecting to a MongoDB via
dsn = "mongodb://#{config.database.username}:#{config.database.password}##{config.database.host}/{config.database.name}"
mongoose.connect(dsn, (err) -> throw err if err)
And most of my writes will be using Models the way I'm supposed to. But there is this one read that I have to do from a Collection and it's Schema-less. Meaning, it's unprocessed data that was stored by another process. How can I successfully read from that then write to other collections using my Schemas?
If I use mongoose, can I not do this?
To start with you can just make a blank schema for it.
var OtherSchema = new Schema({}, {collection: 'your-collection-name'});
Mongoose.model('Other', OtherSchema);
// ..