The docs is output is [] in console, but it not equal to [] even two or three =
or this var Person = mongoose.model('Person', blogSchema);
var newx = function() {
for(var x =1; x<10; x++){
Person.find({short:x},function (err, docs) {
if(docs==[]){
console.log("find!"+x);
return x;
}
})}}
I figure out with docs.length
whole code
But there is another problem this function end after the save Person.
var newx = function() {
var maxvalue=10;
var findvalue;
for(var x =1; x<maxvalue; x++){
console.log((x))
Person.find({short:x},function (err, docs) {
if(docs.length==0){
findvalue =x;
x=maxvalue;
console.log("find!"+findvalue);
console.log((x))
}
})}
var createAndSave = function(passurl) {
console.log("1>: "+passurl);
var x = newx(); console.log("x>: "+x)
var person = new Person({ long:passurl, short:x})
var data=person.save(function(err, person) {
if (err) return console.error (err)
return console.log("2>: "+person)
});
};
The ouput is always maxvalue and ten times and should be only one, because I set the x to maxvalue
the logs
I modified the code I call the function in end of fist instead of passing return value, but the result is always max value in these case 10 and should be the first 1. and change find to findOne that cause the output is not empty array but null if doesn’t exists. so the if(!docs){
var newx =function (url) {
var maxvalue=10;
var findvalue;
for(var x =1; x<maxvalue; x++){
console.log((x))
Person.findOne({short:x},function (err, docs) {
console.log(docs)
if(!docs){
findvalue =x;
x=maxvalue;
console.log((x))
}
})}
console.log("find!"+findvalue);
createAndSave (url,findvalue)}
var createAndSave = function(passurl,x) {
console.log("1>: "+passurl);
console.log("x>: "+x)
var person = new Person({ long:passurl, short:x})
var data=person.save(function(err, person) {
if (err) return console.error (err)
return console.log("2>: "+person)
});
};
Looks like you have a solution but I would recommend using a GUID for a user id field.
In the past I have not used a User Id field and just used email or username as the key field, using a unique field constraint:
The only time I have done something similar, I had all the IDs in state in the front end and worked out the next ID based on this info. So I passed the new ID to the ADD (Insert) function.