Hi ,
i have been updated mongoose node package to version :- 5.0.0
.save method is creating issues which should save the object to db ..
Issue related Code :-
function _save(obj,callback){
var result;
obj.save(function(err) {
if (err) {
callback(err);
} else {
result=obj;
callback();
}
});
}
Error Facing :-
{ Error
at MongooseError (/app/node_modules/mongoose/lib/error/index.js:12:11)
at model.Model.save (/app/node_modules/mongoose/lib/model.js:322:25)
at _save (/app/app/controllers/orders.server.controller.js:84:9)
at /app/app/controllers/orders.server.controller.js:173:13
at /app/app/models/sequence.server.model.js:32:13
at model.Query.
at /app/node_modules/kareem/index.js:297:21
at /app/node_modules/kareem/index.js:135:16
at _combinedTickCallback (internal/process/next_tick.js:73:7)
at process._tickCallback (internal/process/next_tick.js:104:9)
message: 'No matching document found for id "5aa029057c3bbe0013f8d0d6"',
name: 'VersionError' }
Note :- i can able to fetch the document from DB with Id "xxxxxxxxxxxxxxxxxxxxxxx"
Can you guys suggest something to successful save . My Project depoyments and functionalities are halted due to this functionality distrubence
"node": "7.10.1",
"npm": "3.10.1"
"mongoose": "5.0.0"
Hope some one gives me helping advice .. Thanks
Thanks,
Prasad.
Please mention your node.js, mongoose and MongoDB version.
please share your schema and other relevant code. it will help us come to a solution faster. If you can't share your code for whatever reason, please create a complete but minimal example that will help us replicate what you are seeing.
#!/usr/bin/env node
'use strict'
const mongoose = require('mongoose')
mongoose.connect('mongodb://localhost/test')
const Schema = mongoose.Schema
const testSchema = new Schema({
name: String
})
const Test = mongoose.model('test', testSchema)
const test = new Test({ name: 'George' })
test.save(function (err, doc) {
if (err) { return console.error(err) }
return console.log(doc)
})
$ ./example.js
{ name: 'George', _id: 5aa0558c6fb6d2163e5f0037, __v: 0 }
^C
$
@prasad47 Also, when you have time, go to mongoose on gitter or mongoose on slack. Folks are online there and happy to help.
My Code :-
Schema Declaration :-
var mongoose = require('mongoose');
var db = mongoose.connect(url, options , function(err) {
if (err) {
console.error(chalk.red('Could not connect to MongoDB!'));
console.log(chalk.red(err));
}
});
var schema = new mongoose.Schema();
```
exports.xyzSchema= new Schema({ ... },{ versionKey: false });
mongoose.model('xyz', exports.xyzSchema);
Saving the Dynamic Object (obj)
```
var order = new xyz(_.extend({obj:obj});
order .save(function(err) {
if (err) {
callback(err);
} else {
result=order;
}
Error With Versioning False :-
{ DocumentNotFoundError: No document found for query "{ _id: xxxxxxxxxxxx}"
at new DocumentNotFoundError (C:\F-A Workspace\marketplace-api\node_modules\mongoose\lib\error\notFound.js:31:11)
at $__handleSave (C:\F-A Workspace\marketplace-api\node_modules\mongoose\lib\model.js:266:15)
at C:\F-A Workspace\marketplace-api\node_modules\mongoose\lib\model.js:206:9
at args.push (C:\F-A Workspace\marketplace-api\node_modules\mongoose\node_modules\mongodb\lib\utils.js:404:72)
at handleCallback (C:\F-A Workspace\marketplace-api\node_modules\mongoose\node_modules\mongodb\lib\utils.js:128:55)
at C:\F-A Workspace\marketplace-api\node_modules\mongoose\node_modules\mongodb\lib\collection.js:1028:5
at C:\F-A Workspace\marketplace-api\node_modules\mongodb-core\lib\connection\pool.js:541:18
at _combinedTickCallback (internal/process/next_tick.js:131:7)
at process._tickCallback (internal/process/next_tick.js:180:9)
message: 'No document found for query "{ _id: xxxxxxxxxxxxxxx}"',
name: 'DocumentNotFoundError',
query: { _id: xxxxxxxxxxxxxxxx} }
With Versioning True :-
{ Error
at MongooseError (/app/node_modules/mongoose/lib/error/index.js:12:11)
at model.Model.save (/app/node_modules/mongoose/lib/model.js:322:25)
at _save (/app/app/controllers/orders.server.controller.js:84:9)
at /app/app/controllers/orders.server.controller.js:173:13
at /app/app/models/sequence.server.model.js:32:13
at model.Query. (/app/node_modules/mongoose/lib/model.js:3907:16)
at /app/node_modules/kareem/index.js:297:21
at /app/node_modules/kareem/index.js:135:16
at _combinedTickCallback (internal/process/next_tick.js:73:7)
at process._tickCallback (internal/process/next_tick.js:104:9)
message: 'No matching document found for id "5aa029057c3bbe0013f8d0d6"',
name: 'VersionError' }
** FYI These schemas are created with mongoose version 3.8.8 * Actually the errors getting started when we Upgraded to 5.0.0 .. Please suggest .... Thing is same code version Upgrade
Here i am updating the schema to give more clarity
exports.myCartSchema = new Schema({
schemaName:{type: String,default: 'MyCart',required: 'Schema Name cannot be blank'},
displayName : String,
payment:{
method:String,
status:String, //paid or due
},
customer:{
userId:String,
firstName:String,
lastName:String,
email:String,
phone:Number
},
analytics:{
ipAddress:String,
userAgent:String,
referer:String,
cookieId:String
},
referralServer:{
name:''
},
system: {
createdBy: {type: Schema.ObjectId},
dateCreated:{type: Date,default: Date.now},
dateUpdated:{type: Date, default: Date.now},
isEnabled:{type: Boolean,default:true},
isDeleted:{type: Boolean,default:false},
_id:false,
id:false
},
});
var myCart=mongoose.model('myCart', exports.myCartSchema );
@prasad47 was using [email protected]. He upgraded to [email protected].* and gets the error: 'No matching document found for id "5aa253cf91cff8001387748b"',
name: 'VersionError' } now when he tries to save.
it seems to me like there are a few possibilities:
@prasad47, can you add a comment here with the output from db.version() in the mongo shell on the mongodb Server that you are connecting to?
sure
My app connects to the above console with mongo url .. plz take a loook
I spent some more time chatting on this with @prasad47 yesterday. There is a mistake in the above example in the call to save. the lodash extend call is different from his actual code.
@prasad47 can you please update this with an example that matches your real code as closely as possible, or create a standalone example that mirrors the code you wish to remain private minus any details that are sensitive. Feel free to use my example above or one of the gists I shared yesterday and derive as complete a working example as possible.
Hi Guys
Actually there is only small Change from above code bits apart from that i can assure everything is Consistent and it has been Stable in production from 2 years FYI but the version upgrade is the thing which is creating Chaos .. here i am re-posting .. but please don't consider naming conventions stuff because they are properly Maintained .. in the project in model,controller pattern
Server.js File
var mongoose = require('mongoose');
var db = mongoose.connect(url, options , function(err) {
if (err) {
console.error(chalk.red('Could not connect to MongoDB!'));
console.log(chalk.red(err));
}
});
model.js // Start
var Schema = mongoose.Schema,
exports.CartSchema = new Schema({
schemaName:{type: String,default: 'MyCart',required: 'Schema Name cannot be blank'},
displayName : String,
payment:{
method:String,
status:String, //paid or due
},
customer:{
userId:String,
firstName:String,
lastName:String,
email:String,
phone:Number
},
analytics:{
ipAddress:String,
userAgent:String,
referer:String,
cookieId:String
},
referralServer:{
name:''
},
system: {
createdBy: {type: Schema.ObjectId},
dateCreated:{type: Date,default: Date.now},
dateUpdated:{type: Date, default: Date.now},
isEnabled:{type: Boolean,default:true},
isDeleted:{type: Boolean,default:false},
_id:false,
id:false
},
});
var Cart=mongoose.model('Cart', exports.CartSchema );
// End of Model.js
controller.js //Start
var dynamicCart= {
"displayName": "Desktop Cart",
"payment": {
"method": "Cash",
"status": "Paid"
},
"referralServer": {
"name": "none"
},
"analytics": {
"referer": "self",
"userAgent": "Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.186 Safari/537.36"
},
"customer": {
"userId": "58d5d5dssd4d55d4d5d5d45d5",
"email": "[email protected]",
"firstName": "Prasad",
"lastName": "NV",
"phone": 99999999999
},
"system": {
"isDeleted": false,
"isEnabled": true,
"dateUpdated": "2017-03-07T17:54:02.294Z",
"dateCreated": "2017-03-07T17:54:02.294Z"
}
}
var cart= new Cart(_.extend(dynamicCart);
cart.save(function(err) {
if (err) {
callback(err);
} else {
result=cart;
callback(result);
}
controller.js //End
When End Point (route) called the following error happening
Please refer Above Errors
Thanks,
Prasad
what is _saveCreatedOrder
doing? can we see that code
@varunjayaraman I think you will get more clarity When i just deleted the other Errors which are kind of creating more chaos.
Actually _saveCreatedOrder is nothing but a reusable global function which performs save every time ..
_saveCreatedOrder // what ever the method name it is
Code follows : -
function _saveCreatedOrder(obj,callback){ // obj == cart
var result;
obj.save(function(err) {
if (err) {
callback(err);
} else {
result=obj;
callback();
}
});
}
The Filtered Error from the above scenarios is .save method from Mongoose npm is creating Problem ..
{ Error
at MongooseError (/app/node_modules/mongoose/lib/error/index.js:12:11)
at model.Model.save (/app/node_modules/mongoose/lib/model.js:322:25)
at _save (/app/app/controllers/orders.server.controller.js:84:9)
at /app/app/controllers/orders.server.controller.js:173:13
at /app/app/models/sequence.server.model.js:32:13
at model.Query. (/app/node_modules/mongoose/lib/model.js:3907:16)
at /app/node_modules/kareem/index.js:297:21
at /app/node_modules/kareem/index.js:135:16
at _combinedTickCallback (internal/process/next_tick.js:73:7)
at process._tickCallback (internal/process/next_tick.js:104:9)
message: 'No matching document found for id "xxxxxx"',
name: 'VersionError' }
I repeat you guys .. The Problem is .save method from Mongoose npm is creating Problem
I have provided @prasad47 with the following test code to try and isolate the issue to mongoose, mongodb native, and the server. I have redacted the sensitive userID from the code here.
'use strict'
const uri = 'mongodb://localhost/test'
const collectionName = 'testing123'
const mongoose = require('mongoose')
const Schema = mongoose.Schema
const cartSchema = new Schema({
schemaName: { type: String, default: 'MyCart', required: 'Schema Name cannot be blank' },
displayName: String,
payment: {
method: String,
status: String
},
customer: {
userId: String,
firstName: String,
lastName: String,
email: String,
phone: Number
},
analytics: {
ipAddress: String,
userAgent: String,
referer: String,
cookieId: String
},
referralServer: {
name: ''
},
system: {
createdBy: { type: Schema.ObjectId },
dateCreated: { type: Date, default: Date.now },
dateUpdated: { type: Date, default: Date.now },
isEnabled: { type: Boolean, default: true },
isDeleted: { type: Boolean, default: false },
_id: false,
id: false
}
})
const Test = mongoose.model(collectionName, cartSchema)
mongoose.connect(uri)
mongoose.connection.on('open', () => {
Test.findOne({ _id: XXXX }, (err, doc) => {
if (err) {
return console.error(err)
}
if (!doc) {
return console.error('no doc found')
}
console.log(doc)
doc.save((err, saved) => {
if (err) {
return console.error(err)
}
if (!saved) {
return console.error('not saved')
}
mongoose.connection.close()
return console.log(saved)
})
})
})
[EDIT] after receiving a couple of similar reports of "no document found errors" I think it's safe to disregard this comment for now.
@prasad47 has verified that the above example works but his actual codebase is still failing. We're working to sort it out over IM, but since it isn't an issue with mongoose we can close this. If we come up with reproducible issue, we can open a new one.
@prasad47 are you connecting to replicaSet?
No I am not in to replica set
FYI ,
var Tank = mongoose.model('Tank', yourSchema);
var small = new Tank({ size: 'small' });
small.save(function (err) {
if (err) return handleError(err);
// saved!
})
Or
Model.create({ size: 'small' }, function (err, small) {
if (err) return handleError(err);
// saved!
})
This is what the code i used and to save docs it is raising the issue .
you know this is the syntax suggested by mongoose documentation .
{ MongooseError
at new MongooseError (C:\F-A Workspace\marketplace-api\node_modules\mongoose\lib\error\index.js:12:11)
at model.Model.save (C:\F-A Workspace\marketplace-api\node_modules\mongoose\lib\model.js:330:25)
at toExecute.push.callback (C:\F-A Workspace\marketplace-api\node_modules\mongoose\lib\model.js:2060:16)
at C:\F-A Workspace\marketplace-api\node_modules\mongoose\node_modules\async\internal\parallel.js:27:9
at eachOfArrayLike (C:\F-A Workspace\marketplace-api\node_modules\mongoose\node_modules\async\eachOf.js:57:9)
at exports.default (C:\F-A Workspace\marketplace-api\node_modules\mongoose\node_modules\async\eachOf.js:9:5)
at _parallel (C:\F-A Workspace\marketplace-api\node_modules\mongoose\node_modules\async\internal\parallel.js:26:5)
at parallelLimit (C:\F-A Workspace\marketplace-api\node_modules\mongoose\node_modules\async\parallel.js:85:26)
at utils.promiseOrCallback.cb (C:\F-A Workspace\marketplace-api\node_modules\mongoose\lib\model.js:2064:5)
at Object.promiseOrCallback (C:\F-A Workspace\marketplace-api\node_modules\mongoose\lib\utils.js:211:14)
at Function.create (C:\F-A Workspace\marketplace-api\node_modules\mongoose\lib\model.js:2029:16)
at C:\F-A Workspace\marketplace-api\app\controllers\orders.server.controller.js:182:19
at C:\F-A Workspace\marketplace-api\app\models\sequence.server.model.js:37:13
at C:\F-A Workspace\marketplace-api\node_modules\mongoose\lib\model.js:3930:16
at _init (C:\F-A Workspace\marketplace-api\node_modules\mongoose\lib\query.js:2007:5)
at model.Document.init (C:\F-A Workspace\marketplace-api\node_modules\mongoose\lib\document.js:393:5)
at completeOne (C:\F-A Workspace\marketplace-api\node_modules\mongoose\lib\query.js:1993:12)
at cb (C:\F-A Workspace\marketplace-api\node_modules\mongoose\lib\query.js:2361:14)
at C:\F-A Workspace\marketplace-api\node_modules\mongoose\lib\query.js:2461:14
at C:\F-A Workspace\marketplace-api\node_modules\mongoose\lib\utils.js:418:16
at result (C:\F-A Workspace\marketplace-api\node_modules\mongoose\node_modules\mongodb\lib\utils.js:413:17)
at executeCallback (C:\F-A Workspace\marketplace-api\node_modules\mongoose\node_modules\mongodb\lib\utils.js:405:9)
at handleCallback (C:\F-A Workspace\marketplace-api\node_modules\mongoose\node_modules\mongodb\lib\utils.js:128:55)
at C:\F-A Workspace\marketplace-api\node_modules\mongoose\node_modules\mongodb\lib\collection.js:2302:12
at result (C:\F-A Workspace\marketplace-api\node_modules\mongoose\node_modules\mongodb\lib\utils.js:413:17)
at executeCallback (C:\F-A Workspace\marketplace-api\node_modules\mongoose\node_modules\mongodb\lib\utils.js:405:9)
at handleCallback (C:\F-A Workspace\marketplace-api\node_modules\mongoose\node_modules\mongodb\lib\utils.js:128:55)
at C:\F-A Workspace\marketplace-api\node_modules\mongoose\node_modules\mongodb\lib\db.js:340:5
at C:\F-A Workspace\marketplace-api\node_modules\mongodb-core\lib\connection\pool.js:541:18
at _combinedTickCallback (internal/process/next_tick.js:131:7)
at process._tickCallback (internal/process/next_tick.js:180:9)
message: 'No matching document found for id "xxxxxxxxxxxx"',
name: 'VersionError' }
@prasad47, During our conversation on gitter you tried the test script I provided above and reported that it worked without error. The error messages in your last comment are clearly coming from your app and not an isolated test case like the one I provided or the one in the documentation. The syntax from the documentation is correct.
I'm going to step back and allow someone with more experience to take over. I'm always available to answer questions regarding what I've done so far on this issue or help in any reasonable way.
Thanks @lineus for the debugging you've done thus far. @prasad47 can you email me at [email protected] so we can set up a time to debug over skype?
I mailed you@ vkarpov15 @ [email protected] a day ago .. pls take a look thanks !!
Hi vkarpov15 could you confirm your availability .. i work in IST timings i am avaialbe from 9 to 9 IST .. Please confirm your availability . i can adjust my time as per your availability
Hi Guys,
My Issue has been troubleshooted by Mr.Valeri karpov . Valeri Described it as Strange Issue when i Described my problem in detail .
While i am trying to create new Object mongoose is not recognizing the object as New .. it is supposing the object as already exists which is Really Strange . So Valeri suggested a Fix
OBJ.isNew = true
before executing the .save method .. which is worked like a Charm ..
That is really helped me a Lot Mr. Valri !!
Thanks for trying to Help Mr.Lineus . Hope this Answer May help ........+1 it when The solution worked ..
Thanks,
Prasad.
Thanks. Got the same issue and the fix suggested worked for me. Is this fix going to be included in the newer version?
@neeraj24 if you can create a reproducible example that shows the error please open a new issue and include it there. Thanks!
I am also occasionally seeing No document found for query "{ _id: xxxxxx }"
errors in our error reporting. Is there some documentation somewhere as to the cause of this error? This issue doesn't provide much details other than a hack for how to solve it in a particular case.
However, for us this happens very infrequently, and probably not always for the same query, so I'd like to know more about why this error happens in the first place.
@adamreisnz this error happens when you save()
a document that was deleted from the db. Here's an example:
const assert = require('assert');
const mongoose = require('mongoose');
mongoose.set('debug', true);
const GITHUB_ISSUE = `gh6215`;
const connectionString = `mongodb://localhost:27017/${ GITHUB_ISSUE }`;
const { Schema } = mongoose;
run().then(() => console.log('done')).catch(error => console.error(error.stack));
async function run() {
await mongoose.connect(connectionString);
await mongoose.connection.dropDatabase();
const schema = new Schema({ name: String });
const Model = mongoose.model('Test', schema);
const doc = await Model.create({ name: 'foo' });
await Model.deleteMany({});
doc.name = 'bar';
await doc.save();
}
Would it be helpful if we added the original stack trace of the save()
call and the name of the model to the error message? That might help you at least figure out what save()
is causing this error.
@vkarpov15 did you figure out what was happening or does this just add the additional logging?
@adamreisnz I didn't figure out why this was happening for your application. Additional logging may help, we'll continue our discussion in #7844
Most helpful comment
Hi Guys,
My Issue has been troubleshooted by Mr.Valeri karpov . Valeri Described it as Strange Issue when i Described my problem in detail .
While i am trying to create new Object mongoose is not recognizing the object as New .. it is supposing the object as already exists which is Really Strange . So Valeri suggested a Fix
OBJ.isNew = true
before executing the .save method .. which is worked like a Charm ..That is really helped me a Lot Mr. Valri !!
Thanks for trying to Help Mr.Lineus . Hope this Answer May help ........+1 it when The solution worked ..
Thanks,
Prasad.