I have mongoose model file like this
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var testSchema = new Schema({
name: { type: String },
username: { type: String },
provider: { type: String },
accessToken: { type: String },
testId: { type: String }
});
/**Indexing*/
testSchema.index({ testId: 1, accessToken: 1 });
testSchema.statics = {
get: function (id, callback) {
this.findOne({'testId': id}, function(error, items){
callback(error, items);
});
},
create: function (data, callback) {
var test = new this(data);
test.save(callback);
}
};
var test = mongoose.model('test', testSchema);
/** export schema */
module.exports = {
Test: test
};
it is working Good with an express app. But I would like to use this model to view and insert data from command line. So, here is my approch which is not working
var Test = require('./app/model/test').Test;
Test.get({'testId': 1},function(err,res){
if(!err){
console.log(res);
}else{
console.log(err);
}
I see two problems:
you're not calling mongoose.connect() anywhere, so it's not connecting to the database
it looks like you should pass the id as an argument to get(); now you're passing it a query. Try this: Test.get('1', ...)
Related
I want to create a document in my MongoDB database and take the _id of the new document.
This is what I'm doing:
const mongoose = require("mongoose");
const billingSchema = require("./models/billing");
const { ObjectId } = require("bson");
const { MongoClient } = require("mongodb");
const mongouri = "***";
var connection = mongoose.createConnection(mongouri);
var Bills = connection.model("Fatturazione", billingSchema, "Fatturazione");
exports.createBill = (b) => {
return new Promise((resolve, reject) => {
Bills.Create(b, function (err) {
if (err) {
reject(err);
} else {
console.log(mongoose.Types.ObjectId(b._id));
resolve();
}
});
});
};
and this is my Schema:
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
//schema define the structure of the document
const billingSchema = new Schema({
data_fatturazione: {
type: Date,
required: true,
},
data_saldo: {
type: Date,
required: false,
},
totale: {
type: Number,
required: false,
},
pagato: {
type: Boolean,
required: false,
},
});
module.exports = billingSchema;
In the console.log() I want to print the _id of the last inserted document but it prints a non-existing id (it doesn't correspond to the _id of the last created document in the database). I also tried without using mongoose.Types.ObjectId() but it prints undefined. I don't understand where is the problem.
I call the function createBill() in another js file, passing an object with the correct fields.
You are trying to get the _id of argument b, which is passed to your createBill, which is logically undefined. Instead you must get the _id from a result of Bill.create, mongoose callbacks take 2 arguments as #Joe mentioned in the comments, so your code must look like this:
exports.createBill = (b) => {
return new Promise((resolve, reject) => {
Bills.Create(b, function (err, result) {
if (err) {
reject(err);
} else {
console.log(result._id);
resolve(result);
}
});
});
};
i am trying to get the data from mongodb using express server but all i am getting is empty array => []
However if i run the db.Goserv.find() in console i get the results right please help
here is the server.js file
var Schema = mongoose.Schema;
var schema = new Schema({
type: String,
address: String,
servicecost: String
}, { collection: 'Goserv' });
var Goserv = mongoose.model('Goserv', schema );
module.exports = Goserv ;
app.get('/api/centre', function(req, res) {
Goserv.find(function(err, centre){
if(err){
res.send(err);
} else {
res.json(centre);
console.log(centre);
}
});
});
Try this...
var Schema = mongoose.Schema;
var schema = new Schema({
type: String,
address: String,
servicecost: String
}, { collection: 'Goserv' });
var Goserv = mongoose.model('Goserv', schema );
module.exports = Goserv ;
app.get('/api/centre', function(req, res) {
Goserv.find({},function(err, centre){
if(err){
res.send(err);
} else {
res.json(centre);
console.log(centre);
}
});
});
I have tried several different ways to validate a foreign key in Mongoose and cannot figure it out.
I have a schema like this:
//Doctors.js
var schema = mongoose.Schema({
email: { type: String }
}
module.exports = mongoose.model('Doctors', schema);
//Patients.js
var Doctors = require('./Doctors');
var schema = mongoose.Schema({
email: { type: String },
doctor: { type: String, ref: 'Doctors' }
}
schema.pre('save', function (next, req) {
Doctors.findOne({email:req.body.email}, function (err, found) {
if (found) return next();
else return next(new Error({error:"not found"}));
});
});
module.exports = mongoose.model('Patients', schema);
however I get an this error: Uncaught TypeError: Object #<Object> has no method 'findOne'
Anyone know how to do something similar to what I am trying to do here?
I kept googling over the past hour, and saw something about scope that got me thinking. The following code fixed my problem.
//Doctors.js
var mongoose = require('mongoose');
var schema = mongoose.Schema({
email: { type: String }
}
module.exports = mongoose.model('Doctors', schema);
//Patients.js
//var Doctors = require('./Doctors'); --> delete this line
var mongoose = require('mongoose');
var schema = mongoose.Schema({
email: { type: String },
doctor: { type: String, ref: 'Doctors' }
}
schema.pre('save', function (next, req) {
var Doctors = mongoose.model('Doctors'); //--> add this line
Doctors.findOne({email:req.body.email}, function (err, found) {
if (found) return next();
else return next(new Error({error:"not found"}));
});
});
module.exports = mongoose.model('Patients', schema);
Although this was a quick fix, in no way was it an obvious fix (at least to me). The issue was the scope of variables.
I'm getting started with the MEAN STACK, so I took their project (about posting articles), and I'm trying to costomize it in order to get the list of all flows that i can filter with angularjs and also findOne by id.
I followed the same thing that they did for articles to create JS files related to flows (flow is my object). So I have a collection named flows that I imported to the same db used by the MEAN STACK (db == mean-dev) and I tryed this code in:
// myApp/serves/models/flow.js
'use strict';
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
// Flow Schema
var FlowSchema = new Schema({
_id: {
type: Number,
default: ''
},
name: {
type: String,
default: '',
trim: true
},
Clients: {
type: Array,
default: '',
trim: true
},
DP Prot: {
type: String,
default: ''
}
/* And 15 others attributes...*/
});
/** Statics */
FlowSchema.statics.load = function(id, cb) {
this.findOne({
_id: id
}).exec(cb);
};
// Define the collection
mongoose.model('Flow', FlowSchema);
And the controllers code:
// servers/controllers/flows.js
'use strict';
/**
* Module dependencies.
*/
var mongoose = require('mongoose'),
Flow = mongoose.model('Flow'),
_ = require('lodash');
/**
* Find flow by id
*/
exports.flow = function(req, res, next, id) {
Flow.load(id, function(err, flow) {
if (err) return next(err);
if (!flow) return next(new Error('Failed to load flow ' + id));
req.flow = flow;
next();
});
};
/**
* New code count Flows
*/
exports.compte = function(req, res) {
var c;
flow.count({}, function(err, count) {
if (err) return next(err);
c = count;
res.jsonp (count);
});
};
/**
* Show Flow
*/
exports.show = function(req, res) {
res.jsonp(req.flow);
};
/**
* List of Flows
*/
exports.all = function(req, res) {
Flow.find().sort('-name').populate('name', 'application').exec(function(err, flows) {
if (err) {
res.render('error', {
status: 500
});
} else {
res.jsonp(flows);
}
});
};
I added also routes... But it doesn't work, do you think that I made some mistakes? thank you in advance for your help
The documentation shows you how: http://mongoosejs.com/docs/guide.html#collection
You can explicitly choose a collection when creating the Schema:
// Flow Schema
var FlowSchema = new Schema({
/* attributes...*/
}, {
collection: 'my-collection'
});
Or you can set it on the created schema later:
// Flow Schema
var FlowSchema = new Schema({
/* attributes...*/
});
FlowSchema.set('collection', 'my-collection');
This was added in Mongoose 3.4 I believe, so check the verison of Mongoose you are using.
See this post for your query on enforcing a collection name:
Mongoose -- Force collection name
var mySchema = new Schema({
foo: bar
}, { collection: qux });
where qux is your collection, assuming you connected to the correct db in your mongo-connect.
I'd need some help on returning values after saving a new entry to my db using mongoose.
This is how my controller looks:
var userModel = require('../models/users');
module.exports = {
findAll: function(req, res) {
userModel.user.findAll(function(err, users) {
return res.json(users);
});
},
findId: function(req, res) {
var id;
id = req.params.id;
userModel.user.findId(id, function(err, user) {
return res.json(user);
});
},
addUser: function(req, res) {
newUser = new userModel.user;
newUser.username = req.body.username;
newUser.password = req.body.password;
newUser.addUser(function(err, user) {
return res.json(user);
});
}
};
And here's my users.js:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var UserSchema = new Schema({
username: {
type: String,
required: true
},
password: {
type: String,
required: true
}
});
module.exports = {
findAll: UserSchema.statics.findAll = function(cb) {
return this.find(cb);
},
findId: UserSchema.statics.findId = function(id, cb) {
return this.find({
_id: id
}, cb);
},
addUser: UserSchema.methods.addUser = function(cb) {
return this.save(cb);
}
};
This all works ok, but it only returns me the newly added user with addUser. I would like to get all the entries, including the newsly added one, as a return value. Just like using "findAll". How would be able to do this?
Yes, like bernhardw said there doesn't seem to be a way to return anything but the added document with save().
I followed his advice and called findAll() inside addUser() and it all works perfect now -> I can return all my users after saving a new new one. Thanks.