【问题标题】:How to test if a value exists? [duplicate]如何测试一个值是否存在? [复制]
【发布时间】:2017-07-30 12:59:09
【问题描述】:

我正在使用 mongodb 构建一个应用程序,该应用程序在 mongodb 数据库中获取用户的 twitter 时间线,我想检查我从 twitter 获得的推文是否已经存在于我的数据库中,所以我使用 mongodb.find() 函数.

整个函数是这样的:

db.collection.find({'twitterIAlreadyStored.id_str': newTweet.id_str}

然后我想写一个逻辑代码是:

if(exist){
} else {

}

所以我想知道是否有任何方法可以测试 find 的结果是否存在??

【问题讨论】:

  • db.collection.find({'twitterIAlreadyStored.id_str': newTweet.id_str}).length() !== 0 ?

标签: node.js mongodb mongoose database


【解决方案1】:

db.collection.find 仅在您使用mongo shell 时有效。 你所追求的是mongoose 查询,因为你标记了mongoose 我假设你已经设置好了。

假设您的 model 名称是 twitterIAlreadyStored

以及您正在查看的propertyid_str

您要查找的valuenewTweet.id_str

这将是遵循的格式:

var mongoose = require('mongoose');

mongoose.model('MODELNAME').findOne({'PROPERTY': 'VALUE'}, function(error, exist) {
  if(exist && !error){
    //do something
  } else {
    //IF YOU ARE USING EXPRESS.JS, YOU MUST USE RES.SEND() or RES.END() TO TERMINATE THE CONNECTION
    res.status(500).send({"message" : "Not Found"});
    return;
  }
};

express.js 关于 res.send() 和 res.end() 的文档

【讨论】:

  • 非常感谢,您的回答通过一些编辑解决了我的问题..
  • 我只是提供这样的模型名称,因为我的模型在模型目录中:const users = require('../models/users.models');,但它不起作用,错误:MissingSchemaError :尚未为模型“model”注册架构。
猜你喜欢
  • 1970-01-01
  • 2017-07-02
  • 2011-01-29
  • 1970-01-01
  • 2021-11-25
  • 1970-01-01
  • 1970-01-01
  • 2022-01-25
相关资源
最近更新 更多