i have two variable name and place
var name = 'ram';
var place = ['agra','delhi'];
my Schema is like
var Person= new Schema({
about :
{
name: {type : String},
place: {type : String}
}
,
});
I used query
var person = new Person({
about :
{
name : name,
place : place
}
});
person.save(function(){});
but the problem is that place store as a string in database
name : 'ram',
place : 'agra,delhi'
,so when i applying a query for searching place='agra' ,it gives null output.
But when i search place='agra,delhi' it produces result.
I want that this place store as array in database like
name : 'ram',
place : ['agra','delhi']
Please help me in this.
Change your schema to store places as array
var Person= new Schema({
about : [
{
name: {type : String},
places: [{type : String}]
}
],
});
Related
I've tried looking for solutions and I've read parts of the documentation for the $near and $geoNear queries but I have not been successful.
var userSchema = new Schema({
zipcode : {
formatted : {type : String, required : false, default : ""},
geo : { type: [Number], default: [0,0]} // long, lat
}
});
userSchema.index({"zipcode.geo" : '2d'});
ON A DIFFERENT FILE
var locationSchema = new Schema({
formatted : {type : String, unique : false, required : true},
geo : { type: [Number], default: [0,0]}
});
locationSchema.index({geo: '2d'});
var storeSchema = new Schema({
locations : [locationSchema],
});
On my controller
let nearQuery = {
$near : [ user.zipcode.geo[0], user.zipcode.geo[1]],
spherical: true,
$maxDistance: 7000
}
Stores.find(locations : nearQuery).exec(function(error, doc) {
});
But i end up getting the error - "Error: Can't use spherical with Array."
When I remove
spherical : true
I get the error - " planner returned error: unable to find index for $geoNear query"
I know i am doing something wrong, I just cant figure out how to fix it. How can I fix this? or What is the best way of doing this?
Thank you in advance.
Turns out I was using the wrong syntax for the query and was trying to run the query on the locations field, while I should have done it on the locations.geo field.
https://docs.mongodb.com/manual/tutorial/query-a-2d-index/
i want to update my document field "investorCount" as well as one more updation in the same document in a single mongoose Query .
my update query is
Campaign.update({"campaign.campaign_Id":data.campaignId},{$push: {"campaign.investorsDetails":{investorId: id,investedAmount: Amtinv }},$set : {"campaign.investorCount" : this."campaign.investorCount" + 1 }},function(error,update){
if(error){
defered.reject(error);
}else{
console.log(update);
defered.resolve(update);
}
});
return defered.promise;
}
my schema is -
var campaignSchema = new Schema ({
campaign:
{
campaign_Id : {type: Number ,index :{unique:true}},
beneficiaryAccount : {type : String , required:true},
createdBy : {type : String },
investorsDetails : [{
investorId:{type:Number} ,
investedAmount : {type:Number}
}],
investorCount : {type : Number , default : 0}
}});
i use 'this' operator to access the current value of the field but it not work , please help me to solve this
Mongo provides the handy $inc operator just for this:
$inc : {"campaign.investorCount" : 1 }}
this is my scene:
I have 2 collections(tables):Projects and students(the relation is many to many).
My models are:
Project:
var ProjectSchema = new Schema({
name: {
type: String
},
description: {
type: String
},
user : {
type : Mongoose.Schema.Types.ObjectId,
ref : "User"
}
});
Mongoose.model('Project', ProjectSchema);
User:
var Userchema = new Schema({
name: {
type: String
},
surname: {
type: String
},
project : {
type : Mongoose.Schema.Types.ObjectId,
ref : "Project"
}
});
Mongoose.model('User', UserSchema);
In my view I have 2 inputs where receive name and description of project, then have multiselect where choose 1 or multiples users for this project. When I Click OK should:
Create project, and add to user all users selected as objects in BBDD.
Update user, with project asociation.
I try the next, but only funcion if I choose 1 user:
exports.addUserProject = function(req, res) {
var project=new svmp.Project();
project.name=req.body.name;
project.description=req.body.description;
project.user=req.body.user[0]._id;
project.save(function(err,project){
if (err) {
return res.send(400, {
message : getErrorMessage(err)
});
} else {
res.jsonp(project);
}
})
};
The result in my BBDD is the next:
{ "_id" : ObjectId("57a200a38fae140913ac5413"), "user" : ObjectId("578f41ddb0641d961416c3f5"), "name" : "Project1", "Description" : "Project1 Desc","__v" : 0 }
Thanks for your help
First in your schema definition, since the relationship is many-to-many, you should change the ref to an array of the referenced objects. For example change the user property of projectSchema to an array of object ids like so,
var ProjectSchema = new Schema({
name: {
type: String
},
description: {
type: String
},
user : [{
type : Mongoose.Schema.Types.ObjectId,
ref : "User"
}]
});
Do the same for the project property of the userSchema.
Secondly, on this line project.user=req.body.user[0]._id; you are setting the the _id of only the first selected user as the user while ignoring every other selected users. This is why your code only works for one user. Instead, I will suggest you use a simple loop to push all selected users' _id to the project's user property. You can use a forEach loop as given below.
var selectedUsers = req.body.user;
selectedUsers.forEach(function(u){
project.user.push(u._id)
})
You can also do this with a simple for loop if you wish.
I believe the suggestions above should fix the issues you described.
Assuming the following schema, I am trying to save some GeoJSON data with Mongoose
var simpleSchema = new Schema({
properties:{
name:String,
surname:String
},
location : {
type : String,
coordinates : [ Number , Number ]
}
});
This is how I try to save the document
var a = new simple({properties:{name:"a", surname:"b"}, location:{type:"Point", coordinates:[1, 0]}}).save(function(err){...});
However, what I am getting in the database is
ObjectId("542da9ab0882b41855ac3be0"), "properties" : { "name" : "a", "surname" : "b" }, "__v" : 0 }
It looks like the whole location tag and data are missing. Is this a wrong way to define a schema or a wrong way of saving the document?
When using a field named type in an embedded object, you need to use an object to define its type or Mongoose thinks you're defining the type of object itself.
So change your schema definition to:
var simpleSchema = new Schema({
properties:{
name:String,
surname:String
},
location : {
type : { type: String },
coordinates : [ Number , Number ]
}
});
I'm trying to save a document with mongoose according to the doc http://mongoosejs.com/docs/populate.html
First I call parent.save and inside the callback of parent.save I use child.save.
But when I check parent.childs I can see that no child has been added.
The parent schema is Home :
var HomeSchema = new Schema({
password : String,
draft : { type: Boolean, default: true },
edited : { type: Boolean, default: false },
guests : [{type : Schema.Types.ObjectId, ref : 'Guest'}],
_event : {type : Schema.Types.ObjectId, ref : 'Event'}
});
the child schema is Guest :
var GuestSchema = new Schema({
_home : {type : Schema.Types.ObjectId, ref : 'Home'},
firstname : String,
lastname : String,
coming : { type: String, default: 'dnk-coming' },
phone : String,
email : String,
address : String,
edited : { type: Boolean, default: false },
draft : { type: Boolean, default: true }
});
To avoid any misunderstanding, you have to know that this two Schema are included in my user schema :
var userSchema = mongoose.Schema({
homes:[homeSchema.HomeSchema],
events:[eventSchema.EventSchema],
guests:[eventSchema.guestSchema],
});
Now you should have all the required informations to completly understand the execution :
UserModel.findById(user._id, function(err, userFound) {
if (!err) {
/* cleaning draft*/
userFound.homes = that.clean(userFound.homes);
/* setting draft */
var HomeModel = mongoose.model("Home");
var homeModel = new HomeModel();
homeModel.draft = true;
if (userFound.homes === null) {
userFound.homes = [];
}
homeModel.save(function(err) {
if (!err) {
var GuestModel = mongoose.model("Guest");
var guestModel = new GuestModel();
guestModel._home = homeModel._id;
guestModel.save(function(err) {
if (!err) {
// #ma08 : According to the doc this line should'nt be required
//homeModel.guests.push(guestModel._id); so when I use this obviously the id is correctly set but when I try a populate after saving the populate do not work
userFound.homes.push(homeModel);
userFound.guests.push(guestModel);
userFound.save(function(err) {
if (!err) {
successCallback();
}
else {
errorCallback();
}
});
}
});
}
});
This treatement doesn't result in any error. But it doesn't work as intended when I stringify the user.guests I get :
guests:
[ { coming: 'dnk-coming',
edited: false,
draft: true,
_id: 53dcda201fc247c736d87a95,
_home: 53dce0f42d5c1a013da0ca71,
__v: 0 }]
wich is absolutly fine I get the _home id etc...
Then I stringify the user.homes and I get :
homes:
[ { draft: true,
edited: false,
guests: [],
_id: 53dce0f42d5c1a013da0ca71,
__v: 0 } ]
According to the doc guests should be setted, but it's not <-- this is my issue. Please help me to figure out what I'm doing wrong. I could set it manualy but according to the doc it's not suppose to work this way I think.
guestModel.save(function(err) {...
this is wrong because you are embedding the guests in the userSchema.
So skip the guestModel.save and just push the guestModel in userFound
An embedded document can never a reference. You can't point to it without obtaining the parent document. So you can't do both embedding and keeping a ref to the embedded document. You should choose between either embedding or adding a ref.
My suggestion would be to design your schemas like this. Store guests in a separate collection. Store the ref to guest in user and home schemas. If you want to store some relationship data you can store along with the ref like [{guestId:{type:Schema.Types.ObjectId,ref:'Guest'},field1:{type:...},field2:{...}..] and if you just want the ref [{type:Schema.Types.ObjectId,ref:'Guest'}]