i have a problem when i want to include my models with mongoose in nodejs, i'm create a models with schema like this
var mongoose = require('mongoose')
, Schema = mongoose.Schema;
var Users = new Schema({
idUser : {type:String},
username: {type:String}
});
// middleware
Users.pre('save', function (next,done) {
notify(this.get('email') + done);
// something goes wrong
next(new Error('something went wrong'));
});
//registered on mongoose models
mongoose.model("Users",Users);
and i save in folde models/schema.js but i don't know how to call that file in app.js , when i'm try using this code
var mongoose = require('mongoose')
, models = require('./models/schema.js');
//mongoose configurationfor database;
var db = mongoose.connect("mongodb://localhost/vynchat");
var users = mongoose.model("Users");
users.save();
i have error when i try to start sudo node app.js
throw e; // process.nextTick error, or 'error' event on first tick
^
TypeError: Object function model() {
Model.apply(this, arguments);
} has no method 'save'
at Object.<anonymous> (/opt/development/vynapp/app.js:18:7)
at Module._compile (module.js:441:26)
at Object..js (module.js:459:10)
at Module.load (module.js:348:31)
at Function._load (module.js:308:12)
at Array.0 (module.js:479:10)
at EventEmitter._tickCallback (node.js:192:40)
the error model() has no method save... how i can fix this..?
You are calling users.save();
, but, users
is a Model.
The save
methods can be used on instances of models, something like:
var mongoose = require('mongoose')
, models = require('./models/schema');
var db = mongoose.connect("mongodb://localhost/vynchat")
, Users = mongoose.model("Users");
var user = new User({
"your": "data"
});
user.save(function (err, model) {
if (err) throw err;
console.log("My new User is saved",
"`save` hook worked as espected since we had no errors here");
});
You should read the node.js modules API and carefully read mongoose API.
As a side note: when you require('mongoose')
the first time in your code node will give you an instance of the mongoose connector, subsequent requires will yield the same object.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With