如何使用MongooseJS的findOne()并获取结果数组?

时间:2019-02-11 12:58:38

标签: javascript mongoose

我是Mongoose的新手,我不知道如何从mlab获取数据库的结果。

我知道如何找到OneAndUpdate,但是在获取结果时遇到了麻烦。我认为,猫鼬网站在解释如何获得特定结果方面没有提供那么多的信息。

我的MongoDB数据库看起来像这样。集合的名称是TagstoFiles。

enter image description here

我想用猫鼬放回给定标签的所有file_id。

我无法理解如何使用mongoose's site中的findOne和findById。

我尝试编写一些代码,但无济于事。

router.post('/decrypt_download', ensureAuthenticated, function(req, res){
    var tags = req.body.ea;
    var arrayOfFiles = [];
    TagstoFiles.findOne({tag:tags[0]},function(err, file_id){
  var obj = JSON.parse(file_id);

});
//how to use ^
    res.send("Working.");
});

有人可以解释如何实现吗?

1 个答案:

答案 0 :(得分:0)

在这里,我解释了如何使用findOne和findById来找到用法相同的方法,以执行我了解的操作,您需要使用find

var Wanted= require('../models/wanted');

Wanted.findOne({"idsearch":idofwantedele, "secondparam":otherfilter}).exec((err,result) =>{


 if (err) return res.status(500).send({message : "something for an error"});

 if (result ) {
     return res.status(200).send({message: "here the result has the object of type wanted"});
 }

 if (!result ){
  return res.status(400).send({message : "nothing with those filters"});
 }
});

findById

var Wanted= require('../models/wanted');

Wanted.findById(wantedid, (err, result) => {
 if(err) return res.status(500).send({message : "something for an error"});

 if(!result) return res.status(404).send({message : "nothing with those filters"});

 if(result) return res.status(200).send({message:"result is a wanted with wantedid"});

});

模式

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var WantedSchema = Schema({
some: String,
secondparam:String,
reftootherschema: { type: Schema.ObjectId, ref: 'User' },
});

module.exports = mongoose.model('Wanted',WantedSchema);