【发布时间】:2017-10-21 14:31:32
【问题描述】:
这是我的架构。 user_id 和 other_id 应该是唯一的(复合)。
var mongoose = require("mongoose");
var uniqueValidator = require('mongoose-unique-validator');
var Schema = mongoose.Schema;
var FriendshipSchema = new Schema({
user_id: {
type: String,
default: "",
trim: true,
unique:true,
},
other_id: {
type: String,
default: "",
unique:true,
},
status: {
type: String,
index: true,
default: "none",
},
});
FriendshipSchema.plugin(uniqueValidator);
module.exports = mongoose.model('Friendship', FriendshipSchema)
这是我的服务器端代码。使用 Mongoose 非常简单的插入。
app.post('/api/user/friendrequest', function(req, res){
var friendship = new Friendship(req.body);
console.log(req.body);
Friendship.find({}, function (err, docs) {
if (docs.length){
console.log('abac');
}else{
friendship.save(function(err){
if (err)
{
console.log(err)
}
});
}
});
});
我在控制台中收到此响应,但在 MongoDB 中保存的条目不超过 1 个。我也删除了索引,但它仍然无法正常工作。顺便说一句,“user_id”在另一个集合中是唯一的。当我登录console.log(err)时,我也没有收到任何错误。
{ user_id: 'google-oauth2|117175967810648931400',
status: 'pending',
other_id: 'facebook|10209430751350509' }
abac
这里是友谊集合的索引。
db.friendships.getIndexes()
[
{
"v" : 2,
"key" : {
"_id" : 1
},
"name" : "_id_",
"ns" : "kola.friendships"
}
]
【问题讨论】:
标签: node.js mongodb mongoose mongoose-schema