我在我的数据库中填充了一些虚拟数据,我试图添加用户。创建了一个用户对象,但没有任何属性保存...最新什么?
app.get('/setup', function (req, res) {
User.findOne({ name: "Nick" }, function (err, user) {
if (user == undefined) {
var nick = new User({
name: "Nick",
}).save();
res.json({ "success": true, "msg": "user created" });
} else {
res.json({ "success": true, "msg": "user existed" });
}
});
});
调用此返回"用户创建"。这是输出所有用户的方法:
app.get('/users', function(req, res) {
User.find({}, function(err, user) {
res.json(user);
});
});
这里的输出是
[
{
"_id": "565772db5f6f2d1c25e999be",
"__v": 0
},
{
"_id": "5657734ba859fefc1dca77db",
"__v": 0
},
{
"_id": "5657738ba859fefc1dca77dc",
"__v": 0
},
{
"_id": "565774f1cf99a2b81fca1e7f",
"__v": 0
},
{
"_id": "565775f0cf99a2b81fca1e80",
"__v": 0
}
]
我试图添加"尼克"几次没有...任何输入? :d
我的Mongoose模型,与其他模型一起位于自己的Model.js文件中:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
// set up a mongoose model and pass it using module.exports
module.exports = mongoose.model('User', new Schema({
name: String,
password: String,
}));
答案 0 :(得分:5)
鉴于您在用户Schema中有一个名称,您还需要等到save()查询完成然后发送响应:
function ellipsis(elem){
var html=elem.html(), //get the html of the respective element
text=html.split('\n'), //split the html by lines and store it into an array
output=[], //an array to store the final output
char, //an element to store each charachter to process
totalWidth=0, //an array to store the processed width of the text
charCount=0; //an array to count how many charachters are allowed to be shown in each line
$.each(text,function(i,v){ //iterating through the array of lines
charCount=0; //emptying the processed variables
totalWidth=0; //emptying the processed variables
for(x=0;x<v.length;x++){ //iterating through each letter of the text
char=v.substr(x,1); //getting the current charachter
$('body').append('<span class="char" style="font-size='+elem.css('font-size')+';">'+char+'</span>'); //putting the current charachter inside a span and giving the span the font size of the element so that we can get the width of the charachter
totalWidth+=$('.char').width(); //adding the width of the charachter to totalWidth to start comparing the total processed width with the element width
$('.char').remove(); //removing the added span
if(totalWidth<=elem.width()){ //checking if the total width of charachters surpassed the width of the element
charCount++; //if not then allowing another charachter to be shown
}
else{
x=v.length; //if it has surpassed it then exiting the for loop
}
}
if(charCount!=v.length){ //checking if the number of allowed charachters is less than the actual line charachter's length
charCount-=4; //if it is less, taking 3 charachters off (for three dots) and one more for converting the number into the index of the charachter
output.push(v.substr(0,charCount)+'...'); //showing the allowed number of charachters and adding three dots to the end and storing it to the output array
}
else{
output.push(v); //if it is not less than the actual text then add the actual text to the output
}
});
$.each(output,function(i,v){ //iterating through the output values
if(v=='')output.splice(i,1); //removing the empty line breaks
});
output=output.join('<br>'); //getting the text together and recreating the line breaks by putting a br tag between them
elem.html(output); //replacing the new processed value with the old value
}
ellipsis($('.cut-off')); //calling the function on the desired element
答案 1 :(得分:4)
请尝试使用此代码:
app.get('/setup', function (req, res) {
User.findOne({ name: "Nick" }, function (err, user) {
if (!err && user) {
res.json({ "success": true, "msg": "user existed" });
}
else {
var nick = new User({name: "Nick" });
nick.save(function(err){
if(!err)
res.json({ "success": true, "msg": "user created" });
})
}
});
});
答案 2 :(得分:3)
您调用的save()函数不正确,并且遵循其他语言的模式而不是Node.js。
Node.js的工作方式与Java,PHP,Ruby,ASP.net等其他语言完全不同 Javascript本质上完全是异步的,并且Node.js已经作为事件驱动和非阻塞I / O进行了改进。因此,代码执行不会继续进行,除非它已经从它所在的函数收到响应。
因此,在执行save()方法之后,它会回复一个回调函数,向node.js发送完成响应,以便它可以触发其他执行。正确的代码将是
var user = new User({name: 'Nick'});
user.save(function(err, savedUser) {
if(err) return res.send(err);
return res.json({'message': 'User created!', user: savedUser});
});
正如您所看到的那样,只要save()方法完成,它就会在回调中响应响应,即err和savedUser而不是返回它们,并且将在save方法之后的每个代码都被写入在回调中。
如果我们将您的代码暂存一段时间并分析问题所在,
var nick = new User({
name: "Nick",
}).save();
res.json({ "success": true, "msg": "user created" });
当调用save()方法时,node.js将数据和插入触发器一起发送到mongodb,然后继续执行其余的代码。即使数据尚未保存,该代码也会打印“成功”。 因此,Node.js中的几乎每个方法都有一个回调,因为它是最后一个发送完成指示的参数。
答案 3 :(得分:2)
您需要在用户架构中定义 name 键才能保存。
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var userSchema = new Schema({
name: String
});
var User = mongoose.model('User', userSchema);
答案 4 :(得分:2)
这是你的代码,它的工作原理。我仅使用module.exports
更改var User
,因为要在一个页面中收集代码。
那么,可能还有其他问题吗?
祝你好运......var express = require('express')
var mongoose = require('mongoose')
var mongoDBUrl = "mongodb://1.0.0.1:27027/tests"
var app = express()
var Schema = mongoose.Schema;
var User = mongoose.model('User', new Schema({
name: String,
password: String,
}));
/* Mongoose Database connection */
mongoose.connect(mongoDBUrl)
var db = mongoose.connection
db.on('error', console.error.bind(console, 'Mongo connection error:'))
db.once('open', function (callback) {
console.log("MongoDB connection has established")
})
app.get('/setup', function (req, res) {
User.findOne({ name: "Nick" }, function (err, user) {
if (user == undefined) {
var nick = new User({
name: "Nick",
}).save();
res.json({ "success": true, "msg": "user created" });
} else {
res.json({ "success": true, "msg": "user existed" });
}
});
});
app.get('/users', function(req, res) {
console.log("/user works")
User.find({}, function(err, user) {
res.json(user);
});
});
app.listen(1337, function() {
console.log('node-app is listening HTTP port 1337')
})
Postman结果;