在实例化dbUser并在同一实例中给定值时,可以调用函数dbUser.save将数据输入到localhost:mongodb。
var gmailUserSchema = new mongoose.Schema({
displayName: String,
emails: [ { value: String } ],
name: { familyName: String, givenName: String }
})
// compiling our schema into a Model.
var gmailUser = mongoose.model('gmailUser', gmailUserSchema);
var dbUser = new gmailUser ({
displayName: 'profile.displayName',
emails: [{value: 'profile.emails'}] ,
name: { familyName: 'profile.familyName',
givenName: 'profile.givenName' }
});
dbUser.save(function (err) {
if (err) // ...
console.log('could not save');
});
但是,如果我将值放入'dbUser'中,从构造函数中分离出来。
// defining schema
var gmailUserSchema = new mongoose.Schema({
displayName: String,
emails: [ { value: String } ],
name: { familyName: String, givenName: String }
})
// compiling our schema into a Model.
var gmailUser = mongoose.model('gmailUser', gmailUserSchema);
var dbUser = new gmailUser;
dbUser = {
displayName: '1profile.displayName',
emails: [{value: '1profile.emails'}] ,
name: { familyName: '1profile.familyName',
givenName: '1profile.givenName' }
}
dbUser.save(function (err) {
if (err) // ...
console.log('could not save');
});
编译时出现以下错误:
dbUser.save(function (err) {
^
TypeError: Object #<Object> has no method 'save'
at Object.<anonymous> (/Users/apple/Documents/herokuApp/onlymongoose-3.js:65:8)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
答案 0 :(得分:0)
执行此操作时,您将替换原始dbUser对象:
var dbUser = new gmailUser;
dbUser = {
displayName: '1profile.displayName',
emails: [{value: '1profile.emails'}] ,
name: { familyName: '1profile.familyName',
givenName: '1profile.givenName' }
}
您可以通过执行以下操作来单独更新字段:
dbUser.displayName = '1profile.displayName';
dbUser.emails = [{value: '1profile.emails'}];
dbUser.name = { familyName: '1profile.familyName' };
dbUser.givenName = '1profile.givenName';