-
-
Notifications
You must be signed in to change notification settings - Fork 3.8k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Not able to persist array of objects in mongo using mongoose #3249
Comments
Hmmm does it work if you remove the |
@vkarpov15 : I tried using save without id field but even then it is not working. Any idea what can be the possible reason ? Also, I have tried .create but that is also not working. |
@vkarpov15 : Just for information, are you able to reproduce the issue ? Also, if this is a bug, then it will definitely take some time to be solved. Meanwhile, is there any work around which I can use for solving my case ? |
Nope can't repro, below script works fine for me in 4.1.2. Which version are you using? var assert = require('assert');
var mongoose = require('mongoose');
mongoose.set('debug', true);
mongoose.connect('mongodb://localhost/gh3249');
var Schema = mongoose.Schema;
var ProfileSchema = new Schema({
name: String,
PagesData: [{
pageAccessToken: { type: String },
category: String,
name: String,
id: String,
perms: [String]
}]
});
var Profile = mongoose.model('Profile', ProfileSchema);
var newProfile = new Profile();
newProfile.name = "someName";
newProfile.PagesData = [ { pageAccessToken: 'someToken',
category: 'Bags/Luggage',
name: 'someBrandName',
id: '12345',
perms:
[ 'ADMINISTER',
'EDIT_PROFILE',
'CREATE_CONTENT' ] } ];
newProfile.save(function(error, result, numAffected) {
assert.ifError(error);
assert.ok(result.PagesData.length);
Profile.findById(result._id).exec(function(error, doc) {
assert.ifError(error);
assert.ok(doc.PagesData.length);
console.log('done');
process.exit(0);
});
}); |
@vkarpov15 |
I have upgraded to mongoose: 4.1.2. It's still not working for me. For debugging purpose, I tried putting console.log statements at various points in the code. There is one strange behavior which I'm observing.
Final obj is printed as:
|
Do you have any transforms or other options defined in your schema? Below script works fine for me. Try modifying the below script with your actual schema and see if you can give me a standalone example that reproduces this behavior. var assert = require('assert');
var mongoose = require('mongoose');
mongoose.set('debug', true);
mongoose.connect('mongodb://localhost/gh3249');
var Schema = mongoose.Schema;
var ProfileSchema = new Schema({
name: String,
PagesData: [{
pageAccessToken: { type: String },
category: String,
name: String,
id: String,
perms: [String]
}]
});
var Profile = mongoose.model('Profile', ProfileSchema);
var newProfile = new Profile();
newProfile.name = "someName";
newProfile.PagesData = [ { pageAccessToken: 'someToken',
category: 'Bags/Luggage',
name: 'someBrandName',
id: '12345',
perms:
[ 'ADMINISTER',
'EDIT_PROFILE',
'CREATE_CONTENT' ] } ];
newProfile.save(function(error, result, numAffected) {
assert.ifError(error);
assert.ok(result.PagesData.length);
Profile.findById(result._id).exec(function(error, doc) {
assert.ifError(error);
assert.ok(doc.PagesData.length);
console.log('done');
process.exit(0);
});
}); |
I have updated your script but it is working fine in your case. I'm still stuck in my case and will be thankful to you if you can provide any help in this case.
In my case, why newProfile.PagesData is not storing the correct value, please help me. Thanks |
@vkarpov15 |
@vkarpov15 I have a similar problem too. // in req.body
// regions_price: [{title: "wfe", price: 0, min: 0, free: 0}, {title: "wfwff", price: 2, min: 1, free: 30}]
var self = this
, id = req.params.id
, body = req.body;
this.model.findById(id, function(err, doc) {
if (err || !doc) return done(err || new Err.NotFound('Document #' + id + ' not found'));
// in doc.regions_price = [{title: "wfe", price: 0, min: 0, free: 0}];
doc.set(body);
doc.save(function(err, document) {
if (err) return done(err);
// document not contain doc.regions_price[1] = {title: "wfwff", price: 2, min: 1, free: 30};
req.params.id = document.id;
methods['get /:id'].call(self, req, res, done);
});
}); |
in 4.1.0, 4.1.1, 4.1.2 |
As a work around for my problem, I decided to update the array field separately, but somehow it is also not working.
Any idea why is this not working ? I think this is the minimum thing which one can get, right ? Updates: Above query works for simple data fields:
There is something wrong in the array of objects field, that's for sure. I'm surprised why your standalone script is working fine. |
Hmmm @mukulgupta2507 the script you provided gives me the below output:
The output looks like what I expect and One more thing you can try; try removing the |
@vkarpov15
P.S. I'm still trying out different techniques in order to resolve the issue. Thanks Update: Tried by giving directly the object without using any variable, still not working. |
No I mean: var ProfileSchema = new Schema({
name: String,
PagesData: [{
pageAccessToken: { type: String, get: decryptText, set: encryptText },
category: String,
name: String,
id: String,
perms: [String]
}],
type: String // <----- try getting rid of this
}); Also, here's the exact script I'm running that gives me the correct output: var assert = require('assert');
var mongoose = require('mongoose');
var crypto = require('crypto');
mongoose.set('debug', true);
mongoose.connect('mongodb://localhost/gh3249');
var cryptKey = crypto.createHash('sha256').update('Nixnogen').digest();
var iv = "someIv";
var Schema = mongoose.Schema;
var ProfileSchema = new Schema({
name: String,
PagesData: [{
pageAccessToken: { type: String, get: decryptText, set: encryptText },
category: String,
name: String,
id: String,
perms: [String]
}],
//type: String
});
function encryptText(text){
var cipher = crypto.createCipher('aes-256-cbc', cryptKey, iv);
var crypted = cipher.update(text,'utf8','binary');
crypted += cipher.final('binary');
crypted = new Buffer(crypted, 'binary').toString('base64');
return crypted;
}
function decryptText(text){
if (text === null || typeof text === 'undefined' || text === '') {return text;};
text = new Buffer(text, 'base64').toString('binary');
var decipher = crypto.createDecipher('aes-256-cbc', cryptKey, iv);
var dec = decipher.update(text,'binary','utf8');
dec += decipher.final('utf8');
return dec;
}
var Profile = mongoose.model('Profile', ProfileSchema);
var newProfile = new Profile();
newProfile.name = "someName";
var data = [];
var dataObj = {pageAccessToken:'iqULIV8BssssAIFJbchZAla3MF90UFZA6Q', category: 'Bags/Luggage', name: 'someBrandName', id: '12345', perms: [ 'ADMINISTER',
'EDIT_PROFILE',
'CREATE_CONTENT',
'MODERATE_CONTENT',
'CREATE_ADS',
'BASIC_ADMIN' ]};
data.push(dataObj);
newProfile.type = "facebook";
newProfile.PagesData = data;
console.log(JSON.stringify(newProfile));
var obj = newProfile.toObject();
delete obj._id;
Profile.update({type: "facebook"}, obj, {upsert: true},function(err, result){
if(err) {
console.log(err);
}
console.log(result);
}); It's the same as yours, but without the 'type' field. It works either way though, as long as I have a clean database. Also, @chetverikov, can you provide me a standalone script please? Would be very helpful :) |
@vkarpov15 In my code, PagesData is not there before even executing Mongoose.update() command. These few lines are the root cause of the problem from my analysis:
So, what appears to me is that there is somehow no data for pagesData and that's why it is not getting persisted in mongo. So, there is something weird happening in these few lines of code. I tried to reproduce the issue but no luck :( Do you think there is something wrong that is happening over here ? I'm still not sure if this is the root cause of the problem but just wanted to share my findings Thanks |
@vkarpov15 hohoohohoh |
@mukulgupta2507 can you try printing out the value of |
@vkarpov15 |
Another suggestion: try putting a |
@vkarpov15 I want to create a map with a objectId as key and an array of string values as its value. The closest that I can get is:
But somehow this is not working for me. When I perform an update with {upsert: true}, it is not correctly populating the key: value in the map. In fact, I'm not even sure if I have declared the schema correctly. Can you tell me if the schema is correct ? Also, How can I perform an update with {upsert: true} for this schema? Please suggest if the approach is correct or should this be modelled some other way? |
The schema looks correct. How are you using it? Also, why not just store the array 'values' in 'MyOtherCollection'? |
Issue's been stale for a while, re-open if this is still an issue. |
Im trying to populate groups product att with numerous product models
})
}) |
Hi,
I'm trying to persist an array of objects in a document using mongoose. I have tried multiple times but it's not persisting array in document. It places an empty array in document.
Following is my Schema:
I'm trying to save a document with an array of objects using following query:
I tried debugging the mongo commands using
On Debug logs it shows, empty array during insert command execution.
Can anyone please tell me how can I store this array of object in my schema ?
Thanks,
The text was updated successfully, but these errors were encountered: