从帖子表格和角度保存mongodb数据

时间:2014-06-22 08:15:31

标签: angularjs mongodb express

这是我的jade文件(基本上是#stat for id和.for class),我想将它发送到mongodb并保存user.activity

textarea#post-form.form-control(
    rows="4",
    placeholder="Share to world of LinkMe",
    ng-model='user.activity'
)

button#post-btn.btn.btn-primary.pull-right(ng-click="post(user)") Link

这是我的控制器代码:

$scope.post = function(user){
    auth.post(user).then(function(){
        $scope.activity = user.activity;
    })
}

auth.post功能:

post: function(user){
    var deferred = $q.defer();

    var updatedUser = new UsersResource(user);
    updatedUser._id = identity.currentUser._id;

    updatedUser.$update().then(
        function(){
            identity.currentUser.activity = updatedUser.activity;
            deferred.resolve();
        }, 
        function(response){
            deferred.reject(response);
        }
    );

    return deferred.promise;
}

好的是我发现这种情况发生了变化,但它没有保存在数据库中。

这是userSchema:

var userSchema = mongoose.Schema({
    username: {type: String, require: '{PATH} is required' , unique: true},
    firstName: {type: String, require: '{PATH} is required'},
    lastName: {type: String, require: '{PATH} is required'},
    profilePic: {type: String, default: 'imgs/default.jpg'},
    activity: String,
    salt: String,
    hashPass: String,
    roles: [String]
});

我非常感谢帮助:)

P.P。我现在在服务器上有这个:

app.put('/collections/:collectionName/:id', function(req, res, next) {
  req.collection.updateById(req.params.id, {$set:req.body}, {safe:true, multi:false}, function(e, result){
    if (e) return next(e)
    res.send((result===1)?{msg:'success'}:{msg:'error'})
  })
})

现在问题是我有userSchema的User模型,但我没有声明任何集合。我该怎么办 ?

1 个答案:

答案 0 :(得分:1)

您需要在服务器端使用REST接口才能使用Mongo,请看一下:

http://docs.mongodb.org/ecosystem/tools/http-interfaces/#HttpInterface-RESTInterfaces

假设您正在使用带有 Express Mongoose 的Node.js,您将必须按以下方式设置REST api:

var app = express();
var mongoose = require('mongoose');
var database_url = "mongodb://localhost:27017/Database";
var listen_port = 8080; // example port
var collections = ["collection1",...];

mongoose.connect(database_url);

var Model1 = mongoose.model('collection1', userSchema); // <--- your user schema

// example of a getter by id 

app.get('/api/get/:id', function(req, res) {
Model1.find({ _id: req.params.id }, function(err, post){
    res.send(post);
});
});

app.listen(listen_port);

并在package.json文件中设置依赖项,例如

"dependencies" : {
    "express"    : "~3.4.4",
    "mongoose"   : "~3.6.2"
}

然后使用Angular $ http服务以执行对API的异步调用。

https://docs.angularjs.org/api/ng/service/$http