简体   繁体   中英

How to retrieve document in mongoose

I have multiple document in collection having a long string in each document, I want to retrieve one document at time, I dont have anything in document except long string, how can I retrieve that?

I inserted all document in collection using insertMany(), here is my code and output when I retrieved all document

var schema = new mongoose.Schema({
question : String,
id: Number
})

var quizz = mongoose.model('Quiz', schema );

var firstDoc = new quizz({
question: 'question 1',
id: 1
})
var secondDoc = new quizz({
question: 'question 2',
id: 2

var question_data = [firstDoc, secondDoc];

quizz.insertMany(question_data, function(err, res){
  if(err){
   console.log("error occured while saving document object " + err )
 }else{
   console.log("saved data");
 }
})

quizz.findOne({id : '1'}, function(err, res){
if(err){
console.log(err)
}else{
  console.log(res);     
}
})

在此处输入图片说明

insertMany Will return you the list of _id s that have been created for your documents you've inserted. You can then pull out each document based on the _id s individually

quizz.insertMany(question_data, function(err, res){
  if(err){
   console.log("error occured while saving document object " + err )
 }else{
   console.dir(res); // res has the _ids.
   console.log("saved data");
 }
})

http://mongoosejs.com/docs/api.html#model_Model.insertMany

Alternatively if you always want to ensure ordering you could add a sequence column to the question, and/or put all questions inside one quizz.

if you want to do something with the _id of the documents that was inserted into the collection then use the answer of Kevin, but if you want to just do something with them later, you can use .find() which return you all the documents that are in the collection.

quizz.find(function(err, docs) {
  //docs = array of all the docs in the collections
})

if you want specific by id:

quizz.findOne({_id: id},function(err, doc) {
  //doc = the specific doc
})

if you want specific by strong

quizz.findOne({question: "question 3"},function(err, doc) {
  //doc = the first (!!!) doc that have question in his `question` attribute 
})

or if you want all the docs that have question 3 in them:

quizz.find({question: "question 3"},function(err, docs) {
  //docs = array with all the docs that have "question 3" there, (return array even if only 1 found) 
})

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