I'm trying to update the IsActive flag inside the function object, however, it is deeply nested inside the Companies and Factories Objects. Trying to use $ is no use, as it does not work with deeply nested subdocuments. Has anyone found a way to work with this???I expect the IsActive flag to be modified, as right now it can only be reached. I've tried:
$$
List item
Placing the $ at various points i.e. Factories.Functions.$.IsActive
-Concatenating in functionIds
{function deleteFunction(companyId, factoryId, functionId) {
return Companies.update({
"CompanyId": companyId,
"Factories.FactoryId": factoryId,
"Factories.Functions.FunctionId": functionId,
}, {"$set": {"Factories.$.Functions.IsActive": false}}
).then(function (result) {
console.log("Reached", result);
return result
}).catch(function (err) {
logger.log(err);
});
}}
let functionsSchema = new mongoose.Schema({
FunctionId: Number,
Name: String,
ADGroup: String,
IsActive: Boolean,
DateCreated: {
type: Date,
default: Date.now
},
DateModified: {
type: Date,
default: Date.now
}
});
let factorySchema = new mongoose.Schema({
FactoryId: Number,
Name: String,
ADGroup: String,
IsActive: Boolean,
DateCreated: {
type: Date,
default: Date.now
},
DateModified: {
type: Date,
default: Date.now
},
Functions: [functionsSchema]
});
let companySchema = new mongoose.Schema({
CompanyId: Number,
Name: String,
IsActive: Boolean,
DateCreated: {
type: Date,
default: Date.now
},
DateModified: {
type: Date,
default: Date.now
},
Employees: [employeeSchema],
Factories: [factorySchema]
});
Related
I have created this schema for user registration:
let userSchema = new mongoose.Schema({
lname: String,
fname: String,
username: String,
email: String,
password: String,
registrationDate: {
type: Date,
default: Date.now()
},
referedBy: {
type: String,
default: ''
},
referalEnd: {
type: Date,
default: Date.now() + 5*365*24*60*60*1000
},
userRefererId: {
type: String,
default: uniqid()
}
});
As you can see, there is a Date.now function and uniqid function in the schema.
Those functions can be used approximately once every 5 minutes,
because if I create two users a few seconds apart, it generates the same uniqid and shows the same date.
Remove the () from Date.now() and just call Date.now.
I've run into this before, the schema is generated at deployment / start time and not regenerated on each new creation hence why the time is always the same. Its better to generate the date / time outside the new Model().save() call.
let userSchema = new mongoose.Schema({
lname: String,
fname:String,
username: String,
email: String,
password: String,
registrationDate: {
type: Date,
default: function(){return Date.now()}
},
referedBy: {
type:String,
default: ''
},
referalEnd: {
type: Date,
default: function(){ return Date.now() + 5*365*24*60*60*1000}
},
userRefererId: {
type:String,
default: uniqid()
}
});
I want to create Dynamo db tables in node.js script.
In short i want dynamo-db code equivalent to following:
var mongo = require('mongoose');
var MongoDB = mongo.connect('mongodb://localhost:27017/test').connection;
MongoDB.on('error', function(err) { console.log(err.message); });
MongoDB.once('open', function() {
console.log("DynamoDB connection open");
});
var userschema = mongo.Schema({
name: String,
nickname: {type: String,default: ''},
email: String,
phone: String,
type: String,
port : String,
deviceRegId: {type: String,default: ''},
assignFlag: Number,
created: {type: Date,default: Date.now} ,
lastmsg : {type: String,default: ''} ,
lasttime : {type: Date,default: Date.now} ,
loginStatus : {type: Boolean,default: false} ,
isOnline : {type: Boolean,default: false} ,
chats: [{
from: String,
msgfrom: Number,
name: String,
msg: String,
date: {type: Date, default: Date.now},
flag: Number
}]
});
var agent = mongo.model('naveen', userschema);
exports.mongo = mongo;
exports.agent = agent;
I am trying to search similar Dynamo function, but could not find any. Any help would be of great use.
Here is the sample code to create the table if not present and create an item on it with default values.
Please note that you can't have empty value for an attribute on DynamoDB. For example, the nickname can't be set as empty string by default.
For any attribute, if you set an empty value and try to insert the data, DynamoDB will throw a validation exception.
So, default can't be empty string.
Code:-
var dynamoose = require('dynamoose');
dynamoose.AWS.config.update({
accessKeyId: 'AKID',
secretAccessKey: 'SECRET',
region: 'us-east-1'
});
dynamoose.local();
var Schema = dynamoose.Schema;
var userSchema = new Schema({
name: {
type: String,
hashKey: true
},
nickname: String,
email: String,
phone: String,
type: String,
port: String,
deviceRegId: String,
assignFlag: Number,
created: { type: Date, default: Date.now },
lastmsg: { type: String },
lasttime: { type: Date, default: Date.now },
loginStatus: { type: Boolean, default: false },
isOnline: { type: Boolean, default: false },
chats: [{
from: String,
msgfrom: Number,
name: String,
msg: String,
date: { type: Date, default: Date.now },
flag: Number
}]
},
{
throughput: { read: 15, write: 5 }
});
var Table = dynamoose.Table;
var UserDetails = dynamoose.model('UserDetails', userSchema);
var user1 = new UserDetails({ name: 'John' });
user1.save(function (err) {
if (err) { return console.log(err); }
console.log('Added a new item');
});
Sample item created:-
Date value is stored as Number.
I have three tables 'cases', 'partners' and 'casepartners' with the following structure:
cases: id,subject,description
partners: id,name,address
casepartners:case,partner,createdAt
I would like to list all cases by also showing for each case, casepartners records where the case id is the same.
I am using this code:
Case.find().sort('-created').exec(function (err, cases) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
res.json(cases);
}
});
It shows all cases fine, but I would like to also show for each case object a list of casepartners for that case id...
Let's say a few partners got subscribed to the same case and I would like to list all of those partners or just count how many partners got subscribed to that case.
I am using Angularjs to list all cases using the ng-repeat but I am kinda confused if I have to make a separate call to show casepartners records for each case within ng-repeat or attach this in the same function by using some kind of .populate() or something else with the entity relationships.
These are the models defined:
var CaseSchema = new Schema({
subject: {
type: String,
default: '',
trim: true,
required: 'Subject cannot be blank'
},
description: {
type: String,
default: '',
trim: true
},
created: {
type: Date,
default: Date.now
},
customer: {
type: Schema.ObjectId,
ref: 'Customer'
},
category: {
type: Schema.ObjectId,
ref: 'Category'
}
});
var CasePartnerSchema = new Schema({
case: {
type: Schema.ObjectId,
ref: 'Case'
},
partner: {
type: Schema.ObjectId,
ref: 'Partner'
},
created: {
type: Date,
default: Date.now
}
});
var PartnerSchema = new Schema({
name: {
type: String,
trim: true,
default: ''
},
created: {
type: Date,
default: Date.now
},
user: {
type: Schema.ObjectId,
ref: 'User'
}
});
Can anyone help with this?
If possible I would recommend redefining your collections (tables) since having a CasePartner collection is a little redundant.
Instead of having a case and casePartner collection, I would recommend you only have a case collection and then have an array of partners inside of that collection.
Your schema would then look like this:
var CaseSchema = new Schema({
partners: [{
type: mongoose.Schema.Types.ObjectId,
ref: 'Partner'
}],
subject: {
type: String,
default: '',
trim: true,
required: 'Subject cannot be blank'
},
description: {
type: String,
default: '',
trim: true
},
created: {
type: Date,
default: Date.now
},
customer: {
type: Schema.ObjectId,
ref: 'Customer'
},
category: {
type: Schema.ObjectId,
ref: 'Category'
}
});
Your find would then look like this:
Case
.find({})
.sort('-created')
//.populate() populates all info from the partnersSchema for each partner
.populate('partners')
.exec(function(err, cases) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
res.json(cases);
}
});
Check out this for more on MongoDB schema design.
try mongoose-reverse-populate. There is a way called populate in mongoose but that helps you when you are first searching caseparters and populate case types . however what you wanted is kind of reverse of that .
I have this schema
var ArticleSchema = new Schema({
user_id: { type: Schema.ObjectId, ref: "User"},
title: String,
description: String,
content: String,
visible: Boolean,
saved: Boolean,
deleted: {type: Boolean, default: false },
permalink: String,
created_at: { type: Date, default: Date.now },
edited_at: { type: Date, default: Date.now },
tags : [],
comments: {
comment: String,
name: String,
email: String,
date: Date,
deleted: Boolean,
}
});
I want to update the deleted field into the comments array for a specific array.
Here is how I'm doing it.
this.model.update(
{
_id: data.articleId
},
{
$set: { 'comments.$.deleted' : true }
},
function(err, doc){
console.info(doc);
console.info(err);
callback(doc);
});
};
Nothing happens, I tried directly on mongo console and it works.
But not in mongoose. For any reason I got in console.info(), null and 0 as results. The document is never updated.
If I try to update other value not nested it works.
You could try the following:
this.model.update(
{
_id: data.articleId
},
{
$set: { 'comments.deleted' : true }
},
function(err, doc){
console.info(doc);
console.info(err);
callback(doc);
});
};
Your code is not working because the comments field is not an array but an embedded sub-document and the $ positional operator only identifies an element in an array to update without explicitly specifying the position of the element in the array.
I'm having real problems with population on the below schemas. It may not be the best design of models (relatively new to MEAN stacks) but I can get it to populate everything except the Spec model.
// Spec Model
var SpecSchema = new Schema({
time: {
type: Date,
default: Date.now
},
active: {
type: Boolean,
default: 'true'
},
name: String,
desc: String
});
module.exports = mongoose.model('Spec', SpecSchema);
// Thing model
var specsSchema = new Schema({
time: {
type: Date,
default: Date.now
},
spec: {
type: Schema.Types.ObjectId,
ref: 'Spec'
},
value: String,
});
var ThingSchema = new Schema({
time: {
type: Date,
default: Date.now
},
active: {
type: Boolean,
default: true
},
title: String,
specs: [specsSchema]
});
var Thing = mongoose.model('Thing', ThingSchema);
// Set model
var thingsSchema = new Schema({
time: {
type: Date,
default: Date.now
},
active: {
type: Boolean,
default: 'true'
},
thing: {
type: Schema.Types.ObjectId,
ref: 'Thing'
}
});
var SetSchema = new Schema({
user: {
type: Schema.Types.ObjectId,
ref: 'User'
},
time: {
type: Date,
default: Date.now
},
active: {
type: Boolean,
default: 'true'
},
title: String,
things: [thingsSchema]
});
var Set = mongoose.model('Set', SetSchema);
The standard population is fine but i cant for the life of me get the model.populate to work and from all the examples and solutions I have looked at I'm unclear as to what the path should be.
Set.findById(req.params.id)
.populate('things.thing')
.populate('user', '_id name')
.exec(function (err, set) {
if(err) { return handleError(res, err); }
if(!set) { return res.send(404); }
Thing.populate(set,{
path:'things.thing.specs.spec',
select: 'name',
model: Spec
}, function(err, set){
if ( err ) return res.json(400, err);
});
return res.json(set);
});
any pointers in the right direction would be much appreciated.
path:'things.thing.specs.spec',
select: 'name',
model: Spec
should be
path:'things.thing.specs.spec',
select: 'name',
model: 'Spec'