Sorry, this is my first nodeJs app, I'm using SailsJs and this is my code
update: function (req, res) {
Cargo.findOne({id: req.param('id')}).exec(function (err,result) {
result.currency = 2;
if(err) {
console.log(err);
}
result.save(function(err,model){
console.log(err);
console.log(model);
console.log('in');
});
console.log("testing");
})
},
I keep getting "testing" in my console log and not getting any log in save method.
Am I doing it wrong?
Found the issue causing it not going into .save method
My model code are as follow
module.exports = {
tableName: "cargo",
attributes: {
'remark': {
type: 'text'
},
'shipper': {
type: 'integer',
integer: true,
model: 'Company',
columnName:"shipperID",
},
'consignee': {
type: 'integer',
integer: true,
columnName:"consigneeID",
model: 'Company'
},
'packing': {
"type": 'integer',
integer: true,
columnName:"packingID",
equals: function (value) {
return value;
}
},
'commodity': {
'type': "string",
maxLength: 512
},
'status': {
'type': "string",
maxLength: 25
},
'dateIn': {
'type': "datetime"
},
'currency': {
'type': 'integer'
},
'amt': {
'type': 'float'
},
'marking': {
'type': 'string',
maxLength: 25,
required: true
},
'createdAt': {
columnName: 'createdDate'
},
'updatedAt': {
columnName: 'lastModifiedDate'
},
'packages': {
collection: 'CargoPackage',
via: 'cargo'
}
}
};
It's due to "packing" attribute having this "equal" that cause the save method to goes into infinite loop or something. I thought this is a validator for making sure the value is what I want. Well I think its built for other purposes.
I guess for others with similar issues, it will be best to have the model you are working on be as basic as possible to make sure it's not that thing holding up the process.
Related
I am newbie in mongodb world, i was stuck in on Mongoose query.
basically I was developing a chat application for my website. the chat schema of my website shown below
const LiveChat = mongoose.Schema({
members: [String],
messages: [{
sender: String,
reciever: String,
text: String,
seen: {
type: Boolean,
default: false
},
date: {
type: Date,
default: Date.now
}
}],
}, { timestamps: true });
for exapmle collection will looks like this
[
{
"_id":"627749f8dc5927d660f76172",
"members":[
"626a250d11ed1b096883aed1",
"626a234611ed1b096883ae13"
],
"messages":[
{
"sender":"626a250d11ed1b096883aed1",
"reciever":"626a234611ed1b096883ae13",
"text":"hello there!.",
"seen":false,
"_id":"6278b0c38031894a9ceefeae",
"date":"2022-05-09T06:12:19.857Z"
},
{
"sender":"626a250d11ed1b096883aed1",
"reciever":"626a234611ed1b096883ae13",
"text":"how are you?.",
"seen":false,
"_id":"6278b0e18031894a9ceefede",
"date":"2022-05-09T06:12:49.680Z"
},
{
"sender":"626a234611ed1b096883ae13",
"reciever":"626a250d11ed1b096883aed1",
"text":"hello Rupesh",
"seen":false,
"_id":"6278b1438031894a9ceeff98",
"date":"2022-05-09T06:14:27.388Z"
},
{
"sender":"626a234611ed1b096883ae13",
"reciever":"626a250d11ed1b096883aed1",
"text":"we are doing well",
"seen":false,
"_id":"6278b1588031894a9ceeffe0",
"date":"2022-05-09T06:14:48.203Z"
},
{
"sender":"626a250d11ed1b096883aed1",
"reciever":"626a234611ed1b096883ae13",
"text":"okay",
"seen":false,
"_id":"6278b1ed8031894a9cef0099",
"date":"2022-05-09T06:17:17.421Z"
}
],
"createdAt":"2022-05-08T04:41:28.416Z",
"updatedAt":"2022-05-09T06:17:17.420Z",
"__v":0
},
{
"_id":"62762021be68a5e2de8dc2d2",
members: ["626a250d11ed1b096883aed1", "6273bc879ff276ac89f9c4f8"]
"messages":[
{
"sender":"626a250d11ed1b096883aed1",
"reciever":"6273bc879ff276ac89f9c4f8",
"text":"hello there!",
"seen":false,
"_id":"6277ac0ba5fe501f98e1421e",
"date":"2022-05-08T11:39:55.263Z"
},
{
"sender":"626a250d11ed1b096883aed1",
"reciever":"6273bc879ff276ac89f9c4f8",
"text":"can you please tell me what is the date of start a project task",
"seen":false,
"_id":"6277ac30a5fe501f98e1424c",
"date":"2022-05-08T11:40:32.472Z"
},
],
"createdAt":"2022-05-07T07:30:41.447Z",
"updatedAt":"2022-05-08T12:24:31.400Z",
"__v":0
}
]
now i want to set seen:true for all messages into messages array whose sender == "626a250d11ed1b096883aed1" ( sender_id and conversation_id are given from req.body into a API).
for all messages in messages array:
seen:false means message is not seen by reciever
seen:true means message is seen by reciever
i was trying following way into my express API but its not wokring...
cosnt {conversation_id, sender_id} = req.body;
LiveChat.findByIdAndUpdate({ _id: conversation_id },
[{
$set: {
'messages.seen': { $cond: [{ $eq: ['messages.sender', sender_id] }, true, false] }
}
}]
,
{
new: true,
useFindAndModify: true,
}
please help me to write this query...
Here's one way you could do the update using "arrayFilters".
db.collection.update({
"_id": "627749f8dc5927d660f76172" // given _id
},
{
"$set": {
"messages.$[x].seen": true
}
},
{
"arrayFilters": [
{
"x.sender": "626a250d11ed1b096883aed1" // given sender
}
]
})
Try it on mongoplayground.net.
Forgive my limited knowledge im about a week into using Sequelize,
Models.PlannerModel.Builds.findAll({
raw: true,
where: {
ProposedDelivery: { [Op.gt]: moment().format("YYYY-MM-DD") },
description: { [Op.ne]: null },
description: { [Op.ne]: " " },
description: { [Op.not]: null },
},
include: [
{
model: Models.PlannerModel.Unit,
required: true
},
],
the result from the above is as you would expect except all the keys for the fields in the includes are as strings so referencing them in my Pug template/class has to be done with brackets
overall not the end of the world just wondering if im doing something wrong ?
Cheers!
Turn off raw to get nested model objects and also to get plain objects use get({ plain: true}) for each returned model instance:
const builds = await Models.PlannerModel.Builds.findAll({
where: {
ProposedDelivery: { [Op.gt]: moment().format("YYYY-MM-DD") },
[Op.and]: [{
description: { [Op.ne]: null },
}, {
description: { [Op.ne]: " " },
}, {
description: { [Op.not]: null },
}
]
},
include: [
{
model: Models.PlannerModel.Unit,
required: true
},
]
})
const plainBuilds = builds.map(x => x.get({ plain: true }))
Please pay attention that I changed conditions with description. In your version of conditions only the last one will work because JS saves only the last key if there are several same keys in the same object.
When I want to create a new record in sails.js, I receive a logical error.
When I delete the following lines in my Controller, it's working:
amaliat_owner: req.param('amaliat_id') || 0,
place_die_owner: req.param('place_die_id') || 0,
media_place_die_owner: req.param('media_place_die_id') || 0,
media_owner: req.param('media_id') || null,
media_amaliat_owner: req.param('media_amaliat_id') || 0,
My route is:
'POST /delneveshte/create': 'DelneveshteController.create'
My model is:
module.exports = {
attributes: {
body: {
type: 'string',
columnType: 'text'
},
date_time: {
type: 'string',
},
is_confirmed: {
type: 'boolean',
defaultsTo: false
},
likee: {
type: 'number',
columnType: 'integer',
defaultsTo: 0
},
favorite: {
type: 'number',
columnType: 'integer',
defaultsTo: 0
},
user_owner: {
model: 'user',
},
shahid_owner: {
model: 'shahid',
},
amaliat_owner: {
model: 'amaliat',
},
media_place_die_owner: {
model: 'mediaplacedie',
},
place_die_owner: {
model: 'placedie',
},
media_owner: {
model: 'media',
},
media_amaliat_owner: {
model: 'mediaamaliat',
},
user_delneveshte_favorites: {
collection: 'userdelneveshtefavorite',
via: 'delneveshte_owner'
},
user_delneveshte_likes: {
collection: 'userdelneveshtelike',
via: 'delneveshte_owner'
},
},
};
My controller is:
create: async function (req, res, next) {
console.log(req.param('place_die_id'));
Delneveshte.create({
body: req.param('body'),
date_time: req.param('date_time'),
likee: req.param('like') || 0,
favorite: req.param('favorite') || 0,
is_confirmed: req.param('is_confirmed') || 0,
user_owner: req.param('user_id'),
shahid_owner: req.param('shahid_id') || 0,
amaliat_owner: req.param('amaliat_id') || 0,
place_die_owner: req.param('place_die_id') || 0,
media_place_die_owner: req.param('media_place_die_id') || 0,
media_owner: req.param('media_id') || null,
media_amaliat_owner: req.param('media_amaliat_id') || 0,
}, function (err, new_del) {
console.log("1");
if(err){
console.log("2");
return res.json({'status':false});
}
console.log("2");
return res.json({'status':true, 'result':new_del});
});
},
I use postman to send the request as follows:
But I receive the JSON {"status": false} and no record is created in the database. How can I fix my problem?
Some things to clarify:
Can you show the error? You can do that adding it to the json response.
If you put a defaultsTo property in the model, you shouldnt put it in the controller.
You have a lot of associations, so you can't send 0 as value of that associations because 0 is not a valid identifier. You should put a valid id or undefined.
I have one document like that
var ConfigSchema = new Schema({
basicConfig: {
levelId: {
type: Number,
required: true
},
hostId: {
type: Number,
required: true
},
Name: {
type: String,
trim: true
},
Settings: {
Type1: {
// some types here...
}
Type2: {
// some types here...
}
}
},
enrolls: {
name: {type: String},
list: [String]
},
awards: {
enable: {type: Boolean},
Primary: {
amount: {type: Number},
type: {type: String}
}
}
Now I want to find configs with hostId matches 60, and selecting basicConfig field.
Config.findOne({ 'basicConfig.hostId': 60 })
.select('basicConfig').exec(function(err, configs) {
if (err) {
console.error(err);
return ;
}
console.log(configs);
});
However, all fields of this document will be returned. It seems that the select does NOT work? Why?
Output:
{ _id: 555c4144c0bff1541d0e4059,
enrolls: {},
awards: { primary: { PrimarySettings: {}, primaryAck: {} } },
basicConfig:
{ levelId: 24,
hostId: 60,
poolName: 'LC' } }
Also, those following codes have been test, it does not work.
BonusConfig.findOne({ 'basicConfig.hostId': 60 }, 'basicConfig', function(err, configs) {
if (err) {
console.error(err);
return ;
}
console.log(configs);
});
But, without the basicConfig field with select with the following codes, it work well.
BonusConfig.findOne({ 'basicConfig.hostId': 60 })
.select('-basicConfig').exec(function(err, configs) {
if (err) {
console.error(err);
return ;
}
console.log(configs);
});
What's wrong with my codes?
Mongoose version: 3.8.24
Mongodb version: 2.6.7
Edit 1
Here is the query log in mongoose debug mode.
Mongoose: configs.findOne({ 'basicConfig.hostId': 60 }) { fields: { basicConfig: 1 } }
Edit 2
After further investigation.
The output result of Config.findOne({ 'basicConfig.hostId': 60 }).select('basicConfig'):
{ _id: 555c4144c0bff1541d0e4059,
enrolls: {},
awards: { primary: { PrimarySettings: {}, primaryAck: {} } },
basicConfig:
{ levelId: 24,
hostId: 60,
poolName: 'LC' } }
Other fields are empty value except basicConfig. However, I want the result is
{ _id: 555c4144c0bff1541d0e4059,
basicConfig:
{ levelId: 24,
hostId: 60,
poolName: 'LC' } }
Your projection of fields that need to be returned is missing the additional parameter. Try this:
BonusConfig.findOne({ 'basicConfig.hostId': 60 }, {'basicConfig':1}, function(err, configs) {
if (err) {
console.error(err);
return ;
}
console.log(configs);
});
Quoting this
This behavior is by design, but admittedly it's not very well-designed. Mongoose is over-eager when it comes to creating sub-docs when loading from the database. Planning on changing that in v5.
I'm creating a model that needs some validations, but the validations handle an error when I input the correct or wrong data.
What is the right way to configure model validations?
My model is:
return sequelize.define('books', {
id : { type: DataTypes.BIGINT , primaryKey:true, autoIncrement:true },
isbn_10 : { type: DataTypes.BIGINT , allowNull: false,
validate: {
min:10,
max:10
}
},
title : { type: DataTypes.STRING , allowNull: false,
validate: {
isNumeric:true,
min:2,
max:255
}
}, { underscored :true, freezeTableName:true});
And I'm validation on this way:
models.Book.create(req.body)
.success(function(book) { console.log(book); res.render('books/create', { books:models.Book }); })
.error(function(errors) {
console.log(errors);
});
The form input data is:
{ Book:
{ isbn_10: '123123131',
title: '',
cadastrar: 'Submit Query' }}
Thanks.
The problem was solved, I update the sequelize version form 2.0.0.alpha.0 to 2.0.0.dev11 and the validations start to work again.
Thanks.