var LocationSchema = new mongoose.Schema({'type': { type: String }, coordinates : []},{_id:false});
var EventsSchema = new mongoose.Schema({
title:String,
status:String,
location:[new mongoose.Schema({
ll:[LocationSchema],
type:String
},{_id:false})] ,
});
Code to add a document:
function (req,res) {
var event = new Events();
var sLoc = new Location();
var dLoc = new Location();
event.title = req.body.title;
event.startdate = req.body.startdate;
sLoc.coordinates.push(parseFloat(req.body.slong));
sLoc.coordinates.push(parseFloat(req.body.slat));
sLoc.type= "Point";
dLoc.coordinates.push(parseFloat(req.body.dlong));
dLoc.coordinates.push(parseFloat(req.body.dlat));
dLoc.type = "Point";
event.location.push({ll:sLoc,type:"s"});
event.location.push({ll:dLoc,type:"d"});
event.save();
}
When I try to save the document, it give an error -- "Can't extract geo keys from object, malformed geometry?:{ 0: { type: [ -122.1251274, 37.4096933 ] } }"
I am making above query in mongoosejs with nodejs
Please let me know what I am doing wrong.
Related
While sending a post request i written the following code :
var email = req.body.email ;
var newDetails = { email: email };
Details.create(newDetails);
console.log(newDetails);
while sending the request. The console.log shows me the correct details,
However in the mongo shell the only collection that exist is "details" and it's empty .
That's the Mongoose Schema:
var mongoose = require("mongoose");
var DetailsSchema = mongoose.Schema({
email: String
});
module.exports = mongoose.model("Details", DetailsSchema);
I'm using NodeJS.
Thanks in advance.
Your Mongoose Model should be like
const mongoose = require("mongoose");
const Scheme = mongoose.Schema;
const DetailsSchema = new Scheme({
email: String
});
module.exports = mongoose.model("Details", DetailsSchema);
Node js Code should be like
var detailsModel = require('../model/Details.js');//path of mongoose model
var detailsData = new detailsModel();
detailsData.email = req.body.email;
detailsData.save(function (err, savedJob) {
if (err) {
return res.send(err);
} else {
return res.send(savedJob);
}
});
To save data in mongoDB's Database
You can use this way
var detailsData = new detailsModel();
detailsData.save()
.then(business => {
res.status(200).json({'Details': 'newDetails added successfully'});
})
.catch(err => {
res.status(400).send("unable to save to database");
});
With this, you can also handle error easily.
I'm using the plugin
mongoose-auto-increment
and it is working fine.
In the description we have to use it like this
var mongoose = require('mongoose'),
Schema = mongoose.Schema,
autoIncrement = require('mongoose-auto-increment');
var connection = mongoose.createConnection("mongodb://localhost/myDatabase");
autoIncrement.initialize(connection);
var bookSchema = new Schema({
author: { type: Schema.Types.ObjectId, ref: 'Author' },
title: String,
genre: String,
publishDate: Date
});
bookSchema.plugin(autoIncrement.plugin, 'Book');
var Book = connection.model('Book', bookSchema);
I have multiple models where i need to auto increment fields
Do i have to initialize in each model the below line
var connection = mongoose.createConnection("mongodb://localhost/myDatabase");
in each model file (where i need increment function)?
I share the solution i implemented myself
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var autoIncrement = require('mongoose-auto-increment');
var connection = mongoose.createConnection("mongodb://localhost/mydatabase");
autoIncrement.initialize(mongoose.connection);
exports.mongoose = mongoose;
exports.Schema = Schema;
exports.autoIncrement = autoIncrement;
and for the schema file
var mong = require('./db');
var Schema = mong.mongoose.Schema;
var autoIncrement = mong.autoIncrement;
var bookSchema = new Schema({
author: { type: Schema.Types.ObjectId, ref: 'Author' },
title: String,
genre: String,
publishDate: Date
});
bookSchema.plugin(autoIncrement.plugin, 'Book');
module.exports = mong.mongoose.model('Book', bookSchema);
I've schema like this and i', trying to get the document from the array using _id. This is my first Mongo project that I'm working, please help me how can I achieve the. I basically want to retrieve the sub document corresponds to the id and update some data in that.
var PhoneSchema = new mongoose.Schema({
type: String,
number: String
});
var StudentSchema = new mongoose.Schema({
name: String,
dept: String,
phone: [PhoneSchema]
});
var Phone = mongoose.model('Phone',PhoneSchema);
var Student = mongoose.model('Student',StudentSchema);
I've tried the following ways, but none of them are working.
Method 1: When I tried the same in the console it is giving me the parent document along with the sub document that corresponds to the phoneId
Student.findOne({"phone._id":new mongoose.Schema.Types.ObjectId(phoneId) }, {'phone.$':1}, function(err, student) {
}
Method 2: As per the mongoose documentation to retrieve sub documents, in this case I'm getting exception saying phone is undefined
Student.phone.Id(phoneId);
I've fixed this by removing Schema from the below query
Student.findOne({"phone._id":new mongoose.Types.ObjectId(phoneId) }, {'phone.$':1}, function(err, student) {
}
i tried to solve your requirement. The following code did the job.
var PhoneSchema = new mongoose.Schema({
type: String,
number: String
});
var StudentSchema = new mongoose.Schema({
name: String,
dept: String,
phone: [PhoneSchema]
});
var Phone = mongoose.model('Phone',PhoneSchema);
var Student = mongoose.model('Student',StudentSchema);
var newPhone = new Phone({
type: 'ios', number: '9030204942'
});
var newStudent = new Student({
name:'Pankaj',
dept:'cse',
phone:newPhone
});
// newStudent.save(function(err, ph) {
// if (err) return console.error(err);
// });
Student.findOne({"phone._id":mongoose.Types.ObjectId('587e6409e06170ba1708dc21') },{_id:0,phone:1}, function(err, phone) {
if(err){
console.log(err)
}
console.log(phone);
});
Find the following screenshot with result
I am saving an image via monngoose but I cannot find it in mongodb?
My Code
var express = require('express');
var fs = require('fs');
var app=express();
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var imgPath = '\Adpic.jpg';
mongoose.connect('mongodb://localhost:/27017/test');
var schema = new Schema({
img: { data: Buffer, contentType: String }
});
img: { data: Buffer, contentType: String }
});
var An = mongoose.model('An', schema);
app.post('/upload',function(req,res){
var asin = new An();
asin.img.data = fs.readFileSync(imgPath);
asin.img.contentType = 'image/jpg';
asin.save(function (err, a) {
if (err) throw err;
console.error('saved img to mongo');
res.json(a);
});
});
app.listen(3000);
This is model in models.js
var PatientSchema = new mongoose.Schema({
_id : String,
LastName : String,
MiddleName : String,
PatientIntId : String,
Sex : String,
Address1 : String,
City : String,
State : String,
ZipCode : String,
AccountNumber : String,
Ssn : String
});
var PatientInfoMdl = mongoose.model('PatientInfo',PatientSchema);
exports.PatientInfoMdl = PatientInfoMdl;
and my code for accessing data is :
var dbObj = require('../dataBase');
var config = require('../config');<
var moment = require('moment');
var models = require('../models/models');
var orm = require('orm');
var xml2js = require('xml2js');
var fs = require('fs');
var user = models.user;
var PatientInfoMdl = models.PatientInfoMdl;
exports.DisplayUsers = function (req, res) {
var name = '';
dbObj.connect(config.get('mongo'), function () {
PatientInfoMdl.find()({}, function (err, docs) {
if (err)
res.json(err);
else res.render('index', { Patients : docs });
});
});
}
and I am not getting data and what is my mistake?
My mistake is not following the naming conventions of collections in mongoDB.
Is there a convention to name collection in MongoDB?
For example:
Controller.js
var mongoose = require('mongoose');
var User = mongoose.model('User');
module.exports = {
show: function(req, res) {
User.find({}, function(err, users) {
res.render('main', {users: users});
})
}
}
Models:User.js
// require mongoose
var mongoose = require('mongoose');
// create the UserSchema
var UserSchema = new mongoose.Schema({
name: String
})
// register the schema as a model
var User = mongoose.model('User', UserSchema);
module.exports = {User}
routes.js
// here we load the Quote model that we created on the server.js page
var mongoose = require('mongoose');
var User = mongoose.model('User');
// import users
var users = require('../controllers/users.js');
module.exports = function(app) {
app.get('/', function(req, res) {
res.send("Hello");
})
app.get('/user',function(req,res){
users.show(req,res);
})
}