简体   繁体   中英

MongoDB findOne() for retrieving from DB

I am writing code in nodejs/MongoDB and am countering this particular issue which I was hoping to get help with:

I have various schemas defined within my Models and I note that for each of these MongoDB automatically populates a unique id, which is represented by the _id field.

However, I am interested in creating a customized ID, which is basically an integer that auto-increments. I have done so by utilizing the 'mongoose-auto-increment' npm package. For example, in my UserSchema:

UserSchema.plugin(passportLocalMongoose);

module.exports = mongoose.model("User", UserSchema);
autoIncrement.initialize(mongoose.connection);
UserSchema.plugin(autoIncrement.plugin, {
  model: 'UserSchema',
  field: 'user_id',
  startAt: 1,
  incrementBy: 1
});

To speed up my application, I have a seeds.js file which aims to load a bunch of data upon application initialization. However, to make this fully functional, I need a way to access my models and reference them over to other models (for cases when there is a one-to-one and one-to-many relationship). Since the mongoDB default _id is extremely long and there is no way to get the result unless I am actually on the html page and can use the req.params.id function, I have been trying to use mongoDB's findOne function to do this without success.

For example:

var myDocument = User.findOne({user_id: {$type: 25}});
if (myDocument) {
  var myName = myDocument.user_id;
  console.log(myName);
}

However, the result is always 'undefined' even though I know there is a User model saved in my database with a user_id of 25.

Any help would be much appreciated :)

User.findOne({ user_id: 25 }).exec(function (err, record) {
                    if (err) {
                        console.log(err);
                    } else {
                       console.log(record);
                    }
                });

You need to undestand the nature of Node.js. Node.js runs in async nature so you can't get the result here. You need to do with other ways

like:

use callback

use promise

use async/await(ES8)

Try this:

User.findOne({user_id: {$type: 25}}, function (err, myDocument) {
  if (myDocument) {
    var myName = myDocument.user_id;
    console.log(myName);
  } else {
    console.log(err);
  }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM