【问题标题】:How to retrieve document in mongoose如何在猫鼬中检索文档
【发布时间】:2016-12-11 21:39:25
【问题描述】:

我有多个文档在每个文档中都有一个长字符串,我想一次检索一个文档,我在文档中除了长字符串之外没有任何内容,我该如何检索?

我使用 insertMany() 将所有文档插入到集合中,这是我检索所有文档时的代码和输出

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);     
}
})

【问题讨论】:

  • quizz.findOne(function(err, data) { })
  • 我已经编辑了问题

标签: node.js mongodb express mongoose mongoose-schema


【解决方案1】:

insertMany 将返回为您插入的文档创建的_ids 列表。然后您可以根据_ids 单独拉出每个文档

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

或者,如果您总是想确保排序,您可以在问题中添加一个序列列,和/或将所有问题放在一个测验中。

【讨论】:

  • 如果我们想检索集合中的单个文档怎么办?我问这个问题是因为我在文档中没有任何不同的东西,除了我保存的字符串很长我不能写整个问题并说如果这匹配 ant 文档给我,以及由猫鼬本身分配的 ID,这也很长
  • 我认为您只需要在每个文档上都有一个序列,然后使用以下 quizz.findOne({ sequence: 1 }, function (err, doc) { }) 查询它
  • 如果我这样做,我会得到空值
  • 您需要先为每个文档设置sequence 字段。
  • 而不是我添加的序列 id :) 输出正确的值
【解决方案2】:

如果您想对插入到集合中的文档的 _id 做某事,请使用 Kevin 的答案,但如果您想稍后对它们做某事,您可以使用 .find(),它会将您全部返回集合中的文档。

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

如果你想通过 id 指定:

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

如果你想要具体由强

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

或者如果您想要所有包含问题 3 的文档:

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) 
})

【讨论】:

  • 是的,我将 id 作为新属性添加到架构中并最终添加到文档中,以便我可以识别每个文档
  • 好吧,您应该编辑问题以准确告诉我们您想要实现的目标,因为您不需要将 id 添加到文档中,因为一旦您保存文档,猫鼬就会处理它(无需id)
  • 如果我要添加新的属性 id 并使用 findOne(id: number) 进行检索,我会得到 null
  • 本地的,本地id不是mongoose分配的
  • 你在err得到了什么?
猜你喜欢
  • 1970-01-01
  • 2017-01-26
  • 2015-02-23
  • 2020-10-25
  • 2014-08-29
  • 2014-10-30
  • 2017-11-24
  • 2017-09-11
  • 2020-07-02
相关资源
最近更新 更多