我正在尝试将用户保存到数据库,但如果不存在,则创建一个。但它只保存第一个对象(用户)。如果我尝试添加另一个用户,它不想要。有人知道会出现什么问题吗?
模型
var mongoose = require('mongoose');
var uniqueValidator = require('mongoose-unique-validator');
var Schema = mongoose.Schema;
var childSchema = (
{
_id: false,
movieId: {
type: Number,
index: true
},
value: {
type: Number
}
}
);
var user = new Schema({
name: {
type: String
},
movieCollections: [childSchema]
});
clickPoint.plugin(integerValidator);
clickPoint.plugin(uniqueValidator);
//export model...
module.exports = mongoose.model("User", user);
控制器:
var User = require('../Models/user');
User.findOne({name: aName}, function (err, data) {
if(!err) {
//if data was found
if(data) {
console.log('we found somebody');
}
else {
var entry = new User({
name: aName,
movieCollections: [{
movieId: 12355,
value: 23
}]
});
entry.save();
}
}
});
答案 0 :(得分:1)
您可以尝试显示entry.save()的任何错误吗?
entry.save(function(err) {
if (err) console.log(err);
});
修改强>
我认为你必须像这样设置你的架构:
var childSchema = (
{
_id: false,
movieId: {
type: Number,
index: false // Now you can have duplicate movieId
},
value: {
type: Number
}
}
);
希望有所帮助