我想在Mongoose上使用findOne()
在Twitter帐户中查找Twitter JSON凭据中的ObjectId。
我正在使用以下架构和代码:
var userSchema = new Schema({
provider: String,
name: String,
email: String,
username: String,
twitter: JSON
});
User.findOne({
'twitter.id_str': 123
}, function (err, user) {
if (err) {
return done(err);
}
if (!user) {
user = new User({
name: 'Full Name',
email: 'mail@gmail.com',
username: 'pseudo',
provider: 'twitter',
twitter: { id_str: 123 }
});
user.save(function (err) {
if (err) console.log(err);
console.log(user);
});
} else {
console.log(user);
}
});
答案 0 :(得分:0)
将架构更改为:
<!DOCTYPE html>
<html ng-app="plunker">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>
document.write('<base href="' + document.location + '" />');
</script>
<link rel="stylesheet" href="style.css" />
<script data-require="angular.js@1.3.x" src="https://code.angularjs.org/1.3.20/angular.js" data-semver="1.3.20"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
<div id="filter" ng-click="toggleFilter()">
({{gridOptions.enableFiltering ? "-" : "+"}}) {{gridOptions.enableFiltering ? "Dis" : "En"}}able Filtering
</div>
</body>
</html>
或
var userSchema = new Schema({
provider: String,
name: String,
email: String,
username: String,
twitterId: { type: Number, unique: true }
});
第二个更像你当前的设置。如果您使用该架构,那么您的搜索代码可能是一个在var userSchema = new Schema({
provider: String,
name: String,
email: String,
username: String,
twitter: { id: { type: Number, unique: true } }
});
上带有可选upsert
标记的findOne:
findOneAndUpdate()
请参阅此处了解另一个使用示例:How do I update/upsert a document in Mongoose?