How to create field using variable name? - javascript

How can I create a field in mongoose using a variable name? I've seen some ways to do it using .update(), but I was wondering if there was a way to do it when creating a new document
I have my schema like:
var summariesSchema = mongoose.Schema({
type: String,
name: String,
date: String
})
and my object:
var date = '2015-02-01'
var obj = {
ios: 100,
android: 500
}
var doc = {}
doc[date] = obj
var mongoDoc = new Summaries({
name: 'John',
type: 'person',
date: date,
$doc: doc
})
mongoDoc.save(function(err){
if(!err) log('done')
else log(err.toString())
})
But it only saves the fields 'name', 'type' and 'date'.
Can anyone tell me if its possible to do something like that and if so, what am I missing?

Got it..
first part from #Alex is right, just change the schema strict property to false so I can add new fields to my mongo document. For the field name as a variable, I just first created my entire object and then create a new instance of the document:
var summariesSchema = mongoose.Schema({
type: String,
name: String,
date: String
}, { strict: false })
var date = '2015-02-01'
var obj = {
name: 'John',
type: 'person',
date: date
}
obj[date] = {
ios: 100,
android: 500
}
var mongoDoc = new Summaries(obj)
mongoDoc.save(function(err){
if(!err) log('Done.')
else log(err)
}
Success!
EDIT
Three years later ES6 syntax also allows us to do so:
var mongoDoc = await new Summaries({
name: 'John',
type: 'person',
date: date,
[date]: { ios: 100, android: 100 }
}).save();

Change your schema definition to
var summariesSchema = mongoose.Schema({
type: String,
name: String,
date: String
}, { strict: false })

Related

How to fix my mongoose query from randomly failing to find a document that hasn't changed?

My mongoose(5.5.15) query is sometimes able to "findById" the document and "select" the sub-document based on the conditional query provided. However, just one second later (or whatever amount of time) the exact same request fails to return anything back. Nothing is changing on the MongoDb document so it has to be something I am doing wrong.
I have already used the console.log(nextDeliveryDate) to get the date object output when the query seemingly fails and the output of the log seems to be the same (except for the time difference from the previous of course). So the error appears to be completely random and uncontrolled.
const today = new Date();
let nextDeliveryDate = new Date();
nextDeliveryDate.setHours(0);
nextDeliveryDate.setMinutes(0);
nextDeliveryDate.setSeconds(0);
if (today.getDay() < 2) {
nextDeliveryDate.setDate(today.getDate() + (2 - today.getDay()));
} else {
nextDeliveryDate.setDate(today.getDate() + (7 - today.getDay()));
}
const result = await Kitchen.findById(req.query.kitchen).select({
deliveries: {
"$elemMatch": {
delivery_date: {
$gte: nextDeliveryDate
}
}
}
}).exec();
// SCHEMA from a different file
const kitchenSchema = mongoose.Schema({
_id: mongoose.Schema.Types.ObjectId,
_created: Date,
_lastModified: {
type: Date,
default: Date.now
},
name: {
type: String,
required: true,
unique: true
},
location: {
street: String,
unit: String,
city: String,
state: String,
zipcode: Number,
latitude: Number,
longitude: Number
},
routes: [{
type: mongoose.Schema.Types.ObjectId,
ref: 'Routes'
}],
manager: {
type: String
},
employees: [{
type: String
}],
deliveries: [{
_id: mongoose.Schema.Types.ObjectId,
_created: Date,
weekday: Number,
delivery_date: Date,
routes: [{...}],
status: {
type: String,
default: 'preparing'
}
}]
});
So sometimes I get the perfect result that I am expecting (the correct delivery object from the array) and sometimes it just doesn't find anything. Please help. Thanks.

Create function to init model schema

Recently, at an interview, I was given a task that I could not solve. I would be very happy if someone helps to figure out how to solve it!
"Create a function to init model schema. Add method to define relation one-to-one, one-to-many. Model fields should have types. Raise an error when type is not corresponding."
const Card = Model({
number: Number,
pin: String
});
const Post = Model({
title: String,
description: String
});
const User = Model({
name: String,
age: Number,
posts: Model.hasMany(Post),
card: Model.hasOne(Card),
});
User.prototype.hasCard = function() {
return !!this.card;
};
const user = new User({
name: 'User',
age: 25,
posts: [{
title: 'Post1',
description: 'Post description'
}],
card: null
});
console.log(user.hasCard()); //false

Mongoose - save object with objectid

Here I have two schema:
var personSchema = Schema({
_id: Schema.Types.ObjectId,
name: String,
job: {
type: Schema.Types.ObjectId,
ref: 'Job',
}
});
var jobSchema = Schema({
_id: Schema.Types.ObjectId,
title: String,
});
var Job = mongoose.model('Job', jobSchema);
var Person = mongoose.model('Person', personSchema);
Suppose Job has some records:
[{
"_id" : ObjectId("5b46d41e04cfc922949dcfda"),
"Title": "Teacher"
}, ...]
When I have some person objects to insert:
[{
name: 'Peter',
job: 'Teacher'
}, ...]
Do I need to find the Job's _id and convert the job field to ObjectId type before each save? e.g.
Job.findOne({title: p.job}, (j) => {
Person.save({name: p.name, job: j._id}).exec(()=>{
// it's ok!
)}
})
Or I can use the middleware or populate function to make it easy? Thankyou!
While saving your person , you are needing a job for it.
So this is how you can proceed for the same:
Either create a new job / find an existing job.
Assign the found job's objects _id field to your new Person and save the same.
Eg.code
let person = new Person({
name : 'TszHin'
});
Job.findOne({ title : 'Abc'})
.then(function(job){
person.job = job._id;
person.save();
});

Mongodb, storing comments to a specific post

My userSchema looks something like this:
var UserSchema = new Schema({
name: { type: ......},
email: { type..... },
test1: {
[
[0] { test: Array },
[1] { test: Array }
]
}
)};
With a few other objects not included here. In the object that's in test1 there is stored some data to which i want to add or somehow bind an array of comments. The problem is that I'm not sure which is the best way to implement this? If i should create a new commentSchema and somehow connect the comments with the object or how to do it. Can anyone give me some tips on how to implement it?
You can create your schema as follows:
var CommentSchema = new Schema({
user: {type: Schema.Types.ObjectId, ref: 'User', required: true},
message: String,
});
var UserSchema = new Schema({
name: { type: ......},
email: { type..... },
...
test1: {
comments: [CommentSchema]
}
... OR
comments: [CommentSchema]
)};
or if you are trying to do something like posts with comments try
var PostSchema = new Schema({
comments: [CommentSchema]
postBody: String
})
var UserSchema = new Schema({
name: { type: ......},
email: { type..... },
...
posts: [PostSchema]
...
)};

How to save form data as an objects and array of objects to mongodb using loop in node.js?

I am new to MongoDB, I am using Node.js, Express 4 and mongoose(mongoDB) for my project.I stuck to save form data to mongoDB within loop and my model contains Objects and array of objects as well.
Model :
var Subscriber = new Schema({
first_name: String,
emergency_contact_1: {
name: String,
number: [{
type: String
}]
},
residential: {
phone: String,
address: String,
...
},
medications: [
{
visit_id: { type: Object },
name: String,
....
}],
food_allergies: [
{type: String}
],
....
});
Controller :
I want to save data in this way:
var subscriber = new Subscriber();
//Here I am trying to save all form's fields to mongoBD fields.
for (var field in form_data) {
subscriber[field] = form_data[field];
}
subscriber.save(function (err1, instance) {
if (err) {
console.log("error");
return res.send("...");
}
console.log("saved successfully");
}
Normal fields are getting saved properly using above loop but when objects or arrays came then it won't get save to mongoDB.
Any solution ? or any other way to insert/save data through loop to mongoDB model ?
Any help would be appreciated.Thank you..!!
Nodejs
var PersonSchema = new Schema({
name: {
given: {
type: String,
required: true
},
family: {
type: String,
required: true
}
},
children: [PersonSchema]
});
var Person = mongoose.model('Person', PersonSchema);
app.post('/person', function (req, res) {
Person.create(req.body)
.then(function (created) {
console.log(created);
res.json(created.id);
});
});
Client
$.ajax({
url: '/person',
type: 'POST',
data: {
name: {
family: 'Green'
},
children: [{
name: {
given: 'Matt',
family: 'Green'
}
}, {
name: {
given: 'Dave',
family: 'Green'
}
}]
}
})
As you can see, I have nested objects and arrays. This works fine for me :)

Categories